This is an automated email from the ASF dual-hosted git repository. markt pushed a commit to branch 10.1.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/10.1.x by this push: new 2e35be5aa1 Code clean-up - formatting. No functional change. 2e35be5aa1 is described below commit 2e35be5aa18f08f44c1b0652e40b4281e88fd9da Author: Mark Thomas <ma...@apache.org> AuthorDate: Fri Aug 29 19:18:02 2025 +0100 Code clean-up - formatting. No functional change. --- .../catalina/filters/TestAddCharSetFilter.java | 2 +- .../catalina/filters/TestCsrfPreventionFilter.java | 25 +- .../TestRateLimitFilterWithExactRateLimiter.java | 2 +- .../catalina/filters/TestRemoteIpFilter.java | 13 +- .../filters/TestRestCsrfPreventionFilter2.java | 16 +- .../catalina/filters/TesterHttpServletRequest.java | 13 +- .../filters/TesterHttpServletResponse.java | 4 +- .../catalina/ha/context/TestReplicatedContext.java | 3 +- .../apache/catalina/loader/MyAnnotatedServlet.java | 3 +- .../apache/catalina/loader/TestVirtualContext.java | 273 ++++++++------------- .../catalina/loader/TestVirtualWebappLoader.java | 13 +- .../catalina/loader/TestWebappClassLoader.java | 88 ++----- .../TestWebappClassLoaderExecutorMemoryLeak.java | 12 +- .../loader/TestWebappClassLoaderMemoryLeak.java | 13 +- .../loader/TestWebappClassLoaderWeaving.java | 95 +++---- ...sterWebappClassLoaderThreadLocalMemoryLeak.java | 75 +++--- .../catalina/manager/TestHostManagerWebapp.java | 3 +- .../apache/catalina/manager/TestManagerWebapp.java | 21 +- .../catalina/manager/TestManagerWebappSsl.java | 21 +- .../catalina/manager/TestStatusTransformer.java | 13 +- test/org/apache/catalina/mapper/TestMapper.java | 22 +- .../apache/catalina/mbeans/TestRegistration.java | 101 +++----- .../catalina/nonblocking/TestNonBlockingAPI.java | 187 ++++++-------- .../nonblocking/TesterAjpNonBlockingClient.java | 21 +- 24 files changed, 406 insertions(+), 633 deletions(-) diff --git a/test/org/apache/catalina/filters/TestAddCharSetFilter.java b/test/org/apache/catalina/filters/TestAddCharSetFilter.java index f6623579aa..e8a252130a 100644 --- a/test/org/apache/catalina/filters/TestAddCharSetFilter.java +++ b/test/org/apache/catalina/filters/TestAddCharSetFilter.java @@ -115,7 +115,7 @@ public class TestAddCharSetFilter extends TomcatBaseTest { tomcat.start(); - Map<String, List<String>> headers = new HashMap<>(); + Map<String,List<String>> headers = new HashMap<>(); getUrl("http://localhost:" + getPort() + "/", new ByteChunk(), headers); String ct = getSingleHeader("Content-Type", headers).toLowerCase(Locale.ENGLISH); diff --git a/test/org/apache/catalina/filters/TestCsrfPreventionFilter.java b/test/org/apache/catalina/filters/TestCsrfPreventionFilter.java index 9b5634b7c9..8cf872dda8 100644 --- a/test/org/apache/catalina/filters/TestCsrfPreventionFilter.java +++ b/test/org/apache/catalina/filters/TestCsrfPreventionFilter.java @@ -101,11 +101,15 @@ public class TestCsrfPreventionFilter extends TomcatBaseTest { @Test public void testNoNonceBuilders() { - Assert.assertEquals(CsrfPreventionFilter.PrefixPredicate.class, CsrfPreventionFilter.createNoNoncePredicate(null, "/images/*").getClass()); - Assert.assertEquals(CsrfPreventionFilter.SuffixPredicate.class, CsrfPreventionFilter.createNoNoncePredicate(null, "*.png").getClass()); - Assert.assertEquals(CsrfPreventionFilter.PatternPredicate.class, CsrfPreventionFilter.createNoNoncePredicate(null, "/^(/images/.*|.*\\.png)$/").getClass()); + Assert.assertEquals(CsrfPreventionFilter.PrefixPredicate.class, + CsrfPreventionFilter.createNoNoncePredicate(null, "/images/*").getClass()); + Assert.assertEquals(CsrfPreventionFilter.SuffixPredicate.class, + CsrfPreventionFilter.createNoNoncePredicate(null, "*.png").getClass()); + Assert.assertEquals(CsrfPreventionFilter.PatternPredicate.class, + CsrfPreventionFilter.createNoNoncePredicate(null, "/^(/images/.*|.*\\.png)$/").getClass()); - Collection<Predicate<String>> chain = CsrfPreventionFilter.createNoNoncePredicates(null, "*.png,/js/*,*.jpg,/images/*,mime:*/png,mime:image/*"); + Collection<Predicate<String>> chain = CsrfPreventionFilter.createNoNoncePredicates(null, + "*.png,/js/*,*.jpg,/images/*,mime:*/png,mime:image/*"); Assert.assertEquals(6, chain.size()); Iterator<Predicate<String>> items = chain.iterator(); @@ -116,11 +120,13 @@ public class TestCsrfPreventionFilter extends TomcatBaseTest { Assert.assertEquals(CsrfPreventionFilter.PrefixPredicate.class, items.next().getClass()); Predicate<String> item = items.next(); Assert.assertEquals(CsrfPreventionFilter.MimePredicate.class, item.getClass()); - Assert.assertEquals(CsrfPreventionFilter.SuffixPredicate.class, ((CsrfPreventionFilter.MimePredicate)item).getPredicate().getClass()); + Assert.assertEquals(CsrfPreventionFilter.SuffixPredicate.class, + ((CsrfPreventionFilter.MimePredicate) item).getPredicate().getClass()); item = items.next(); Assert.assertEquals(CsrfPreventionFilter.MimePredicate.class, item.getClass()); - Assert.assertEquals(CsrfPreventionFilter.PrefixPredicate.class, ((CsrfPreventionFilter.MimePredicate)item).getPredicate().getClass()); + Assert.assertEquals(CsrfPreventionFilter.PrefixPredicate.class, + ((CsrfPreventionFilter.MimePredicate) item).getPredicate().getClass()); } @Test @@ -130,7 +136,7 @@ public class TestCsrfPreventionFilter extends TomcatBaseTest { Predicate<String> suffix = new CsrfPreventionFilter.SuffixPredicate(".png"); Predicate<String> regex = new CsrfPreventionFilter.PatternPredicate("^(/images/.*|.*\\.png)$"); - for(String url : urls) { + for (String url : urls) { Assert.assertTrue("Prefix match fails", prefix.test(url)); Assert.assertTrue("Suffix match fails", suffix.test(url)); Assert.assertTrue("Pattern match fails", regex.test(url)); @@ -159,7 +165,8 @@ public class TestCsrfPreventionFilter extends TomcatBaseTest { @Test public void testNoNonceMimeMatcher() { MimeTypeServletContext context = new MimeTypeServletContext(); - Predicate<String> mime = new CsrfPreventionFilter.MimePredicate(context, new CsrfPreventionFilter.PrefixPredicate("image/")); + Predicate<String> mime = + new CsrfPreventionFilter.MimePredicate(context, new CsrfPreventionFilter.PrefixPredicate("image/")); context.setMimeType("image/png"); Assert.assertTrue("MIME match fails", mime.test("/images/home.png")); @@ -191,6 +198,7 @@ public class TestCsrfPreventionFilter extends TomcatBaseTest { private static class MimeTypeServletContext extends TesterServletContext { private String mimeType; + public void setMimeType(String type) { mimeType = type; } @@ -200,6 +208,7 @@ public class TestCsrfPreventionFilter extends TomcatBaseTest { return mimeType; } } + private static class NonEncodingResponse extends TesterHttpServletResponse { @Override diff --git a/test/org/apache/catalina/filters/TestRateLimitFilterWithExactRateLimiter.java b/test/org/apache/catalina/filters/TestRateLimitFilterWithExactRateLimiter.java index 6eacfd081c..90d3c048cc 100644 --- a/test/org/apache/catalina/filters/TestRateLimitFilterWithExactRateLimiter.java +++ b/test/org/apache/catalina/filters/TestRateLimitFilterWithExactRateLimiter.java @@ -191,7 +191,7 @@ public class TestRateLimitFilterWithExactRateLimiter extends TomcatBaseTest { * complete. Do comparisons in milliseconds. */ long expectedDuration = (i + 1) * timePerRequest; - long duration = (System.nanoTime() - start)/1000000; + long duration = (System.nanoTime() - start) / 1000000; if (expectedDuration > duration) { sleep(expectedDuration - duration); } diff --git a/test/org/apache/catalina/filters/TestRemoteIpFilter.java b/test/org/apache/catalina/filters/TestRemoteIpFilter.java index ad14ff6fa6..a1a7744612 100644 --- a/test/org/apache/catalina/filters/TestRemoteIpFilter.java +++ b/test/org/apache/catalina/filters/TestRemoteIpFilter.java @@ -739,7 +739,7 @@ public class TestRemoteIpFilter extends TomcatBaseTest { public void testWithTomcatServer() throws Exception { // mostly default configuration : enable "x-forwarded-proto" - Map<String, String> remoteIpFilterParameter = new HashMap<>(); + Map<String,String> remoteIpFilterParameter = new HashMap<>(); remoteIpFilterParameter.put("protocolHeader", "x-forwarded-proto"); // SETUP @@ -766,8 +766,9 @@ public class TestRemoteIpFilter extends TomcatBaseTest { getTomcatInstance().start(); // TEST - HttpURLConnection httpURLConnection = (HttpURLConnection) new URL( - "http://localhost:" + tomcat.getConnector().getLocalPort() + "/test").openConnection(); + 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"); @@ -789,7 +790,7 @@ public class TestRemoteIpFilter extends TomcatBaseTest { public void testJSessionIdSecureAttributeMissing() throws Exception { // mostly default configuration : enable "x-forwarded-proto" - Map<String, String> remoteIpFilterParameter = new HashMap<>(); + Map<String,String> remoteIpFilterParameter = new HashMap<>(); remoteIpFilterParameter.put("protocolHeader", "x-forwarded-proto"); // SETUP @@ -815,8 +816,8 @@ public class TestRemoteIpFilter extends TomcatBaseTest { getTomcatInstance().start(); - Map<String, List<String>> resHeaders = new HashMap<>(); - Map<String, List<String>> reqHeaders = new HashMap<>(); + Map<String,List<String>> resHeaders = new HashMap<>(); + Map<String,List<String>> reqHeaders = new HashMap<>(); String expectedRemoteAddr = "my-remote-addr"; List<String> forwardedFor = new ArrayList<>(1); forwardedFor.add(expectedRemoteAddr); diff --git a/test/org/apache/catalina/filters/TestRestCsrfPreventionFilter2.java b/test/org/apache/catalina/filters/TestRestCsrfPreventionFilter2.java index 21233bce05..d1c2ca1fa2 100644 --- a/test/org/apache/catalina/filters/TestRestCsrfPreventionFilter2.java +++ b/test/org/apache/catalina/filters/TestRestCsrfPreventionFilter2.java @@ -170,8 +170,8 @@ public class TestRestCsrfPreventionFilter2 extends TomcatBaseTest { private void testInvalidPostWithRequestParams() throws Exception { String validBody = Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + validNonce; String invalidbody1 = Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + INVALID_NONCE_1; - String invalidbody2 = Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + - Constants.CSRF_REST_NONCE_HEADER_FETCH_VALUE; + String invalidbody2 = + Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + Constants.CSRF_REST_NONCE_HEADER_FETCH_VALUE; doTest(METHOD_POST, REMOVE_ALL_CUSTOMERS, CREDENTIALS, validBody.getBytes(StandardCharsets.ISO_8859_1), USE_COOKIES, HttpServletResponse.SC_FORBIDDEN, null, null, true, Constants.CSRF_REST_NONCE_HEADER_REQUIRED_VALUE); @@ -186,8 +186,8 @@ public class TestRestCsrfPreventionFilter2 extends TomcatBaseTest { private void doTest(String method, String uri, BasicCredentials credentials, byte[] body, boolean useCookie, int expectedRC, String expectedResponse, String nonce, boolean expectCsrfRH, String expectedCsrfRHV) throws Exception { - Map<String, List<String>> reqHeaders = new HashMap<>(); - Map<String, List<String>> respHeaders = new HashMap<>(); + Map<String,List<String>> reqHeaders = new HashMap<>(); + Map<String,List<String>> respHeaders = new HashMap<>(); addNonce(reqHeaders, nonce, n -> Objects.nonNull(n)); @@ -232,7 +232,7 @@ public class TestRestCsrfPreventionFilter2 extends TomcatBaseTest { } } - private void addCookies(Map<String, List<String>> reqHeaders, Predicate<List<String>> tester) { + private void addCookies(Map<String,List<String>> reqHeaders, Predicate<List<String>> tester) { if (tester.test(cookies)) { StringBuilder cookieHeader = new StringBuilder(); boolean first = true; @@ -248,20 +248,20 @@ public class TestRestCsrfPreventionFilter2 extends TomcatBaseTest { } } - private void addNonce(Map<String, List<String>> reqHeaders, String nonce, Predicate<String> tester) { + private void addNonce(Map<String,List<String>> reqHeaders, String nonce, Predicate<String> tester) { if (tester.test(nonce)) { addRequestHeader(reqHeaders, Constants.CSRF_REST_NONCE_HEADER_NAME, nonce); } } - private void addCredentials(Map<String, List<String>> reqHeaders, BasicCredentials credentials, + private void addCredentials(Map<String,List<String>> reqHeaders, BasicCredentials credentials, Predicate<BasicCredentials> tester) { if (tester.test(credentials)) { addRequestHeader(reqHeaders, CLIENT_AUTH_HEADER, credentials.getCredentials()); } } - private void addRequestHeader(Map<String, List<String>> reqHeaders, String key, String value) { + private void addRequestHeader(Map<String,List<String>> reqHeaders, String key, String value) { List<String> valueList = new ArrayList<>(1); valueList.add(value); reqHeaders.put(key, valueList); diff --git a/test/org/apache/catalina/filters/TesterHttpServletRequest.java b/test/org/apache/catalina/filters/TesterHttpServletRequest.java index 2f24746cfa..c75ac07371 100644 --- a/test/org/apache/catalina/filters/TesterHttpServletRequest.java +++ b/test/org/apache/catalina/filters/TesterHttpServletRequest.java @@ -50,8 +50,8 @@ import jakarta.servlet.http.PushBuilder; public class TesterHttpServletRequest implements HttpServletRequest { - private final Map<String, Object> attributes = new HashMap<>(); - private final Map<String, List<String>> headers = new HashMap<>(); + private final Map<String,Object> attributes = new HashMap<>(); + private final Map<String,List<String>> headers = new HashMap<>(); private String method; private String scheme; private String serverName; @@ -118,7 +118,7 @@ public class TesterHttpServletRequest implements HttpServletRequest { * This test implementation is hard coded to return an empty Hashmap. */ @Override - public Map<String, String[]> getParameterMap() { + public Map<String,String[]> getParameterMap() { return new HashMap<>(); } @@ -463,10 +463,11 @@ public class TesterHttpServletRequest implements HttpServletRequest { */ @Override public <T extends HttpUpgradeHandler> T upgrade(Class<T> httpUpgradeHandlerClass) - throws IOException, ServletException { + throws IOException, ServletException { try { return httpUpgradeHandlerClass.getDeclaredConstructor().newInstance(); - }catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException ignore){ + } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | + IllegalAccessException ignore) { } return null; @@ -483,7 +484,7 @@ public class TesterHttpServletRequest implements HttpServletRequest { } @Override - public Map<String, String> getTrailerFields() { + public Map<String,String> getTrailerFields() { throw new RuntimeException("Not implemented"); } diff --git a/test/org/apache/catalina/filters/TesterHttpServletResponse.java b/test/org/apache/catalina/filters/TesterHttpServletResponse.java index 5f8d52d783..3fac321b80 100644 --- a/test/org/apache/catalina/filters/TesterHttpServletResponse.java +++ b/test/org/apache/catalina/filters/TesterHttpServletResponse.java @@ -366,11 +366,11 @@ public class TesterHttpServletResponse implements HttpServletResponse { /* NOOP */} @Override - public void setTrailerFields(Supplier<Map<String, String>> supplier) { + public void setTrailerFields(Supplier<Map<String,String>> supplier) { /* NOOP */ } @Override - public Supplier<Map<String, String>> getTrailerFields() { + public Supplier<Map<String,String>> getTrailerFields() { return null; } } diff --git a/test/org/apache/catalina/ha/context/TestReplicatedContext.java b/test/org/apache/catalina/ha/context/TestReplicatedContext.java index 3230df06b5..3840a19249 100644 --- a/test/org/apache/catalina/ha/context/TestReplicatedContext.java +++ b/test/org/apache/catalina/ha/context/TestReplicatedContext.java @@ -64,8 +64,7 @@ public class TestReplicatedContext extends TomcatBaseTest { private static final long serialVersionUID = 1L; @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { getServletContext().setAttribute("NULL", null); resp.getWriter().print("OK"); } diff --git a/test/org/apache/catalina/loader/MyAnnotatedServlet.java b/test/org/apache/catalina/loader/MyAnnotatedServlet.java index 68e472a622..00b5691475 100644 --- a/test/org/apache/catalina/loader/MyAnnotatedServlet.java +++ b/test/org/apache/catalina/loader/MyAnnotatedServlet.java @@ -31,8 +31,7 @@ public class MyAnnotatedServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("test/plain"); resp.getWriter().println(MESSAGE); } diff --git a/test/org/apache/catalina/loader/TestVirtualContext.java b/test/org/apache/catalina/loader/TestVirtualContext.java index a377d7458a..9b45373919 100644 --- a/test/org/apache/catalina/loader/TestVirtualContext.java +++ b/test/org/apache/catalina/loader/TestVirtualContext.java @@ -49,8 +49,7 @@ public class TestVirtualContext extends TomcatBaseTest { // present. The listener affects the JVM, and thus not only the current, // but also the subsequent tests that are run in the same JVM. So it is // fair to add it in every test. - tomcat.getServer().addLifecycleListener( - new JreMemoryLeakPreventionListener()); + tomcat.getServer().addLifecycleListener(new JreMemoryLeakPreventionListener()); } @Test @@ -60,36 +59,27 @@ public class TestVirtualContext extends TomcatBaseTest { File appDir = new File("test/webapp-virtual-webapp/src/main/webapp-a"); // app dir is relative to server home - StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test", - appDir.getAbsolutePath()); + StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); ctx.setResources(new StandardRoot(ctx)); File f1 = new File("test/webapp-virtual-webapp/target/classes"); File f2 = new File("test/webapp-virtual-library/target/WEB-INF"); - File f3 = new File( - "test/webapp-virtual-webapp/src/main/webapp-a/WEB-INF/classes"); - File f4 = new File( - "test/webapp-virtual-webapp/src/main/webapp-b/WEB-INF/classes"); + File f3 = new File("test/webapp-virtual-webapp/src/main/webapp-a/WEB-INF/classes"); + File f4 = new File("test/webapp-virtual-webapp/src/main/webapp-b/WEB-INF/classes"); File f5 = new File("test/webapp-virtual-webapp/src/main/misc"); File f6 = new File("test/webapp-virtual-webapp/src/main/webapp-b"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", f1.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF", - f2.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF", f2.getAbsolutePath(), + null, "/"); + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", f3.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", f4.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/other", - f5.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/", - f6.getAbsolutePath(), null, "/"); + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/other", f5.getAbsolutePath(), + null, "/"); + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/", f6.getAbsolutePath(), null, + "/"); StandardJarScanner jarScanner = new StandardJarScanner(); jarScanner.setScanAllDirectories(true); @@ -98,77 +88,54 @@ public class TestVirtualContext extends TomcatBaseTest { tomcat.start(); - assertPageContains("/test/classpathGetResourceAsStream.jsp?path=nonexistent", - "resourceAInWebInfClasses=true", 404); - - assertPageContains( - "/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceA.properties", - "resourceAInWebInfClasses=true"); - assertPageContains( - "/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceA.properties", - "resourceAInWebInfClasses=true"); - - assertPageContains( - "/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceB.properties", - "resourceBInTargetClasses=true"); - assertPageContains( - "/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceB.properties", - "resourceBInTargetClasses=true"); - - assertPageContains( - "/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceC.properties", - "resourceCInDependentLibraryTargetClasses=true"); - assertPageContains( - "/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceC.properties", - "resourceCInDependentLibraryTargetClasses=true"); - - assertPageContains( - "/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceD.properties", - "resourceDInPackagedJarInWebInfLib=true"); - assertPageContains( - "/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceD.properties", - "resourceDInPackagedJarInWebInfLib=true"); - - assertPageContains( - "/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceG.properties", - "resourceGInWebInfClasses=true"); - assertPageContains( - "/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceG.properties", - "resourceGInWebInfClasses=true"); + assertPageContains("/test/classpathGetResourceAsStream.jsp?path=nonexistent", "resourceAInWebInfClasses=true", + 404); + + assertPageContains("/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceA.properties", + "resourceAInWebInfClasses=true"); + assertPageContains("/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceA.properties", + "resourceAInWebInfClasses=true"); + + assertPageContains("/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceB.properties", + "resourceBInTargetClasses=true"); + assertPageContains("/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceB.properties", + "resourceBInTargetClasses=true"); + + assertPageContains("/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceC.properties", + "resourceCInDependentLibraryTargetClasses=true"); + assertPageContains("/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceC.properties", + "resourceCInDependentLibraryTargetClasses=true"); + + assertPageContains("/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceD.properties", + "resourceDInPackagedJarInWebInfLib=true"); + assertPageContains("/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceD.properties", + "resourceDInPackagedJarInWebInfLib=true"); + + assertPageContains("/test/classpathGetResourceAsStream.jsp?path=rsrc/resourceG.properties", + "resourceGInWebInfClasses=true"); + assertPageContains("/test/classpathGetResourceUrlThenGetStream.jsp?path=rsrc/resourceG.properties", + "resourceGInWebInfClasses=true"); // test listing all possible paths for a classpath resource String allUrls = - getUrl( - "http://localhost:" + getPort() + - "/test/classpathGetResources.jsp?path=rsrc/").toString(); - Assert.assertTrue( - allUrls, - allUrls.indexOf("/test/webapp-virtual-webapp/src/main/webapp-a/WEB-INF/classes/rsrc") > 0); - Assert.assertTrue( - allUrls, - allUrls.indexOf("/test/webapp-virtual-webapp/src/main/webapp-b/WEB-INF/classes/rsrc") > 0); - Assert.assertTrue( - allUrls, - allUrls.indexOf("/test/webapp-virtual-webapp/src/main/webapp-a/WEB-INF/lib/rsrc.jar!/rsrc") > 0); - Assert.assertTrue( - allUrls, - allUrls.indexOf("/test/webapp-virtual-webapp/target/classes/rsrc") > 0); - Assert.assertTrue( - allUrls, - allUrls.indexOf("/test/webapp-virtual-library/target/WEB-INF/classes/rsrc") > 0); + getUrl("http://localhost:" + getPort() + "/test/classpathGetResources.jsp?path=rsrc/").toString(); + Assert.assertTrue(allUrls, + allUrls.indexOf("/test/webapp-virtual-webapp/src/main/webapp-a/WEB-INF/classes/rsrc") > 0); + Assert.assertTrue(allUrls, + allUrls.indexOf("/test/webapp-virtual-webapp/src/main/webapp-b/WEB-INF/classes/rsrc") > 0); + Assert.assertTrue(allUrls, + allUrls.indexOf("/test/webapp-virtual-webapp/src/main/webapp-a/WEB-INF/lib/rsrc.jar!/rsrc") > 0); + Assert.assertTrue(allUrls, allUrls.indexOf("/test/webapp-virtual-webapp/target/classes/rsrc") > 0); + Assert.assertTrue(allUrls, allUrls.indexOf("/test/webapp-virtual-library/target/WEB-INF/classes/rsrc") > 0); // check that there's no duplicate in the URLs String[] allUrlsArray = allUrls.split("\\s+"); - Assert.assertEquals(new HashSet<>(Arrays.asList(allUrlsArray)).size(), - allUrlsArray.length); + Assert.assertEquals(new HashSet<>(Arrays.asList(allUrlsArray)).size(), allUrlsArray.length); String allRsrsc2ClasspathUrls = - getUrl( - "http://localhost:" + getPort() + - "/test/classpathGetResources.jsp?path=rsrc-2/").toString(); - Assert.assertTrue( - allRsrsc2ClasspathUrls, - allRsrsc2ClasspathUrls.indexOf("/test/webapp-virtual-webapp/src/main/webapp-b/WEB-INF/classes/rsrc-2") > 0); + getUrl("http://localhost:" + getPort() + "/test/classpathGetResources.jsp?path=rsrc-2/").toString(); + Assert.assertTrue(allRsrsc2ClasspathUrls, allRsrsc2ClasspathUrls + .indexOf("/test/webapp-virtual-webapp/src/main/webapp-b/WEB-INF/classes/rsrc-2") > 0); // tests context.getRealPath @@ -179,71 +146,39 @@ public class TestVirtualContext extends TomcatBaseTest { // Real paths depend on the OS and this test has to work on all // platforms so use File to convert the path to a platform specific form - File f = new File( - "test/webapp-virtual-webapp/src/main/webapp-a/rsrc/resourceF.properties"); - assertPageContains( - "/test/contextGetRealPath.jsp?path=/rsrc/resourceF.properties", - f.getPath()); + File f = new File("test/webapp-virtual-webapp/src/main/webapp-a/rsrc/resourceF.properties"); + assertPageContains("/test/contextGetRealPath.jsp?path=/rsrc/resourceF.properties", f.getPath()); // tests context.getResource then the content - assertPageContains("/test/contextGetResource.jsp?path=/nonexistent", - "resourceAInWebInfClasses=true", 404); - assertPageContains( - "/test/contextGetResource.jsp?path=/WEB-INF/classes/rsrc/resourceA.properties", - "resourceAInWebInfClasses=true"); - assertPageContains( - "/test/contextGetResource.jsp?path=/WEB-INF/classes/rsrc/resourceG.properties", - "resourceGInWebInfClasses=true"); - assertPageContains( - "/test/contextGetResource.jsp?path=/rsrc/resourceE.properties", - "resourceEInDependentLibraryTargetClasses=true"); - assertPageContains( - "/test/contextGetResource.jsp?path=/other/resourceI.properties", - "resourceIInWebapp=true"); - assertPageContains( - "/test/contextGetResource.jsp?path=/rsrc-2/resourceJ.properties", - "resourceJInWebapp=true"); + assertPageContains("/test/contextGetResource.jsp?path=/nonexistent", "resourceAInWebInfClasses=true", 404); + assertPageContains("/test/contextGetResource.jsp?path=/WEB-INF/classes/rsrc/resourceA.properties", + "resourceAInWebInfClasses=true"); + assertPageContains("/test/contextGetResource.jsp?path=/WEB-INF/classes/rsrc/resourceG.properties", + "resourceGInWebInfClasses=true"); + assertPageContains("/test/contextGetResource.jsp?path=/rsrc/resourceE.properties", + "resourceEInDependentLibraryTargetClasses=true"); + assertPageContains("/test/contextGetResource.jsp?path=/other/resourceI.properties", "resourceIInWebapp=true"); + assertPageContains("/test/contextGetResource.jsp?path=/rsrc-2/resourceJ.properties", "resourceJInWebapp=true"); String allRsrcPaths = - getUrl( - "http://localhost:" + getPort() + - "/test/contextGetResourcePaths.jsp?path=/rsrc/").toString(); - Assert.assertTrue( - allRsrcPaths, - allRsrcPaths.indexOf("/rsrc/resourceF.properties") > 0); - Assert.assertTrue( - allRsrcPaths, - allRsrcPaths.indexOf("/rsrc/resourceE.properties") > 0); - Assert.assertTrue( - allRsrcPaths, - allRsrcPaths.indexOf("/rsrc/resourceH.properties") > 0); + getUrl("http://localhost:" + getPort() + "/test/contextGetResourcePaths.jsp?path=/rsrc/").toString(); + Assert.assertTrue(allRsrcPaths, allRsrcPaths.indexOf("/rsrc/resourceF.properties") > 0); + Assert.assertTrue(allRsrcPaths, allRsrcPaths.indexOf("/rsrc/resourceE.properties") > 0); + Assert.assertTrue(allRsrcPaths, allRsrcPaths.indexOf("/rsrc/resourceH.properties") > 0); // check that there's no duplicate in the URLs String[] allRsrcPathsArray = allRsrcPaths.split("\\s+"); - Assert.assertEquals(new HashSet<>(Arrays.asList(allRsrcPathsArray)).size(), - allRsrcPathsArray.length); + Assert.assertEquals(new HashSet<>(Arrays.asList(allRsrcPathsArray)).size(), allRsrcPathsArray.length); String allRsrc2Paths = - getUrl( - "http://localhost:" + getPort() + - "/test/contextGetResourcePaths.jsp?path=/rsrc-2/").toString(); - Assert.assertTrue( - allRsrc2Paths, - allRsrc2Paths.indexOf("/rsrc-2/resourceJ.properties") > 0); - - assertPageContains( - "/test/testTlds.jsp", - "worldA"); - assertPageContains( - "/test/testTlds.jsp", - "worldB"); - assertPageContains( - "/test/testTlds.jsp", - "worldC"); - assertPageContains( - "/test/testTlds.jsp", - "worldD"); + getUrl("http://localhost:" + getPort() + "/test/contextGetResourcePaths.jsp?path=/rsrc-2/").toString(); + Assert.assertTrue(allRsrc2Paths, allRsrc2Paths.indexOf("/rsrc-2/resourceJ.properties") > 0); + + assertPageContains("/test/testTlds.jsp", "worldA"); + assertPageContains("/test/testTlds.jsp", "worldB"); + assertPageContains("/test/testTlds.jsp", "worldC"); + assertPageContains("/test/testTlds.jsp", "worldD"); } @Test @@ -252,32 +187,28 @@ public class TestVirtualContext extends TomcatBaseTest { File appDir = new File("test/webapp-virtual-webapp/src/main/webapp-a"); // app dir is relative to server home - StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test", - appDir.getAbsolutePath()); + StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); File tempFile = File.createTempFile("virtualWebInfClasses", null); File additionWebInfClasses = new File(tempFile.getAbsolutePath() + ".dir"); Assert.assertTrue(additionWebInfClasses.mkdirs()); File targetPackageForAnnotatedClass = - new File(additionWebInfClasses, - MyAnnotatedServlet.class.getPackage().getName().replace('.', '/')); + new File(additionWebInfClasses, MyAnnotatedServlet.class.getPackage().getName().replace('.', '/')); Assert.assertTrue(targetPackageForAnnotatedClass.mkdirs()); - try (InputStream annotatedServletClassInputStream = this.getClass().getResourceAsStream( - MyAnnotatedServlet.class.getSimpleName() + ".class"); - FileOutputStream annotatedServletClassOutputStream = new FileOutputStream(new File( - targetPackageForAnnotatedClass, MyAnnotatedServlet.class.getSimpleName() - + ".class"))) { + try (InputStream annotatedServletClassInputStream = + this.getClass().getResourceAsStream(MyAnnotatedServlet.class.getSimpleName() + ".class"); + FileOutputStream annotatedServletClassOutputStream = + new FileOutputStream(new File(targetPackageForAnnotatedClass, + MyAnnotatedServlet.class.getSimpleName() + ".class"))) { IOTools.flow(annotatedServletClassInputStream, annotatedServletClassOutputStream); } ctx.setResources(new StandardRoot(ctx)); File f1 = new File("test/webapp-virtual-webapp/target/classes"); File f2 = new File("test/webapp-virtual-library/target/WEB-INF/classes"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", f1.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", f2.getAbsolutePath(), null, "/"); tomcat.start(); @@ -290,14 +221,11 @@ public class TestVirtualContext extends TomcatBaseTest { // then test that if we configure StandardContext with the additional // path, the servlet is detected ctx.setResources(new StandardRoot(ctx)); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", f1.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", f2.getAbsolutePath(), null, "/"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), null, "/"); tomcat.start(); @@ -307,26 +235,23 @@ public class TestVirtualContext extends TomcatBaseTest { Assert.assertTrue("Failed to clean up [" + tempFile + "]", tempFile.delete()); } - private void assertPageContains(String pageUrl, String expectedBody) - throws IOException { + private void assertPageContains(String pageUrl, String expectedBody) throws IOException { assertPageContains(pageUrl, expectedBody, 200); } - private void assertPageContains(String pageUrl, String expectedBody, - int expectedStatus) throws IOException { + private void assertPageContains(String pageUrl, String expectedBody, int expectedStatus) throws IOException { ByteChunk res = new ByteChunk(); // Note: With a read timeout of 3s the ASF CI buildbot was consistently - // seeing failures with this test. The failures were due to the - // JSP initialisation taking longer than the read timeout. The - // root cause of this is the frequent poor IO performance of the - // VM running the buildbot instance. Increasing this to 10s should - // avoid these failures. - // With the additional of Travis CI, failures continued to - // observed with a 10s timeout. It was therefore increased to 20s - // and then 30s. - int sc = getUrl("http://localhost:" + getPort() + pageUrl, res, 30000, - null, null); + // seeing failures with this test. The failures were due to the + // JSP initialisation taking longer than the read timeout. The + // root cause of this is the frequent poor IO performance of the + // VM running the buildbot instance. Increasing this to 10s should + // avoid these failures. + // With the additional of Travis CI, failures continued to + // observed with a 10s timeout. It was therefore increased to 20s + // and then 30s. + int sc = getUrl("http://localhost:" + getPort() + pageUrl, res, 30000, null, null); Assert.assertEquals(expectedStatus, sc); diff --git a/test/org/apache/catalina/loader/TestVirtualWebappLoader.java b/test/org/apache/catalina/loader/TestVirtualWebappLoader.java index 460341740d..67bf9f17eb 100644 --- a/test/org/apache/catalina/loader/TestVirtualWebappLoader.java +++ b/test/org/apache/catalina/loader/TestVirtualWebappLoader.java @@ -48,8 +48,7 @@ public class TestVirtualWebappLoader extends TomcatBaseTest { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); - StandardContext ctx = (StandardContext) tomcat.addContext("", - appDir.getAbsolutePath()); + StandardContext ctx = (StandardContext) tomcat.addContext("", appDir.getAbsolutePath()); loader.setContext(ctx); ctx.setLoader(loader); @@ -70,8 +69,7 @@ public class TestVirtualWebappLoader extends TomcatBaseTest { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); - StandardContext ctx = (StandardContext) tomcat.addContext("", - appDir.getAbsolutePath()); + StandardContext ctx = (StandardContext) tomcat.addContext("", appDir.getAbsolutePath()); WebappLoader loader = new WebappLoader(); @@ -83,13 +81,12 @@ public class TestVirtualWebappLoader extends TomcatBaseTest { ctx.resourcesStart(); File f1 = new File("test/webapp-fragments/WEB-INF/lib"); - ctx.getResources().createWebResourceSet( - WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib", + ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib", f1.getAbsolutePath(), null, "/"); loader.start(); String[] repos = loader.getLoaderRepositories(); - Assert.assertEquals(5,repos.length); + Assert.assertEquals(5, repos.length); loader.stop(); repos = loader.getLoaderRepositories(); @@ -98,7 +95,7 @@ public class TestVirtualWebappLoader extends TomcatBaseTest { // no leak loader.start(); repos = loader.getLoaderRepositories(); - Assert.assertEquals(5,repos.length); + Assert.assertEquals(5, repos.length); // clear loader ctx.setLoader(null); diff --git a/test/org/apache/catalina/loader/TestWebappClassLoader.java b/test/org/apache/catalina/loader/TestWebappClassLoader.java index 3c51239cef..cfb638375c 100644 --- a/test/org/apache/catalina/loader/TestWebappClassLoader.java +++ b/test/org/apache/catalina/loader/TestWebappClassLoader.java @@ -42,8 +42,7 @@ public class TestWebappClassLoader extends TomcatBaseTest { Tomcat tomcat = getTomcatInstance(); - StandardContext ctx = - (StandardContext)tomcat.addContext("", f.getAbsolutePath()); + StandardContext ctx = (StandardContext) tomcat.addContext("", f.getAbsolutePath()); tomcat.start(); @@ -63,49 +62,18 @@ public class TestWebappClassLoader extends TomcatBaseTest { @Test public void testFilter() throws IOException { - String[] classSuffixes = new String[]{ - "", - "some.package.Example" - }; - - String[] resourceSuffixes = new String[]{ - "", - "some/path/test.properties", - "some/path/test" - }; - - String[] prefixes = new String[]{ - "", - "resources", - "WEB-INF", - "WEB-INF.classes", - "WEB-INF.lib", - "org", - "org.apache", - "jakarta", - "javax", - "com.mycorp" - }; - - String[] prefixesPermit = new String[]{ - "org.apache.tomcat.jdbc", - "jakarta.servlet.jsp.jstl", - }; - - String[] prefixesDeny = new String[]{ - "org.apache.catalina", - "org.apache.coyote", - "org.apache.el", - "org.apache.jasper", - "org.apache.juli", - "org.apache.naming", - "org.apache.tomcat", - "jakarta.annotation", - "jakarta.el", - "jakarta.servlet", - "jakarta.websocket", - "jakarta.security.auth.message" - }; + String[] classSuffixes = new String[] { "", "some.package.Example" }; + + String[] resourceSuffixes = new String[] { "", "some/path/test.properties", "some/path/test" }; + + String[] prefixes = new String[] { "", "resources", "WEB-INF", "WEB-INF.classes", "WEB-INF.lib", "org", + "org.apache", "jakarta", "javax", "com.mycorp" }; + + String[] prefixesPermit = new String[] { "org.apache.tomcat.jdbc", "jakarta.servlet.jsp.jstl", }; + + String[] prefixesDeny = new String[] { "org.apache.catalina", "org.apache.coyote", "org.apache.el", + "org.apache.jasper", "org.apache.juli", "org.apache.naming", "org.apache.tomcat", "jakarta.annotation", + "jakarta.el", "jakarta.servlet", "jakarta.websocket", "jakarta.security.auth.message" }; try (WebappClassLoader loader = new WebappClassLoader()) { String name; @@ -113,33 +81,27 @@ public class TestWebappClassLoader extends TomcatBaseTest { for (String prefix : prefixes) { for (String suffix : classSuffixes) { name = prefix + "." + suffix; - Assert.assertTrue("Class '" + name + "' failed permit filter", - !loader.filter(name, true)); + Assert.assertTrue("Class '" + name + "' failed permit filter", !loader.filter(name, true)); if (prefix.equals("")) { name = suffix; - Assert.assertTrue("Class '" + name + "' failed permit filter", - !loader.filter(name, true)); + Assert.assertTrue("Class '" + name + "' failed permit filter", !loader.filter(name, true)); } if (suffix.equals("")) { name = prefix; - Assert.assertTrue("Class '" + name + "' failed permit filter", - !loader.filter(name, true)); + Assert.assertTrue("Class '" + name + "' failed permit filter", !loader.filter(name, true)); } } prefix = prefix.replace('.', '/'); for (String suffix : resourceSuffixes) { name = prefix + "/" + suffix; - Assert.assertTrue("Resource '" + name + "' failed permit filter", - !loader.filter(name, false)); + Assert.assertTrue("Resource '" + name + "' failed permit filter", !loader.filter(name, false)); if (prefix.equals("")) { name = suffix; - Assert.assertTrue("Resource '" + name + "' failed permit filter", - !loader.filter(name, false)); + Assert.assertTrue("Resource '" + name + "' failed permit filter", !loader.filter(name, false)); } if (suffix.equals("")) { name = prefix; - Assert.assertTrue("Resource '" + name + "' failed permit filter", - !loader.filter(name, false)); + Assert.assertTrue("Resource '" + name + "' failed permit filter", !loader.filter(name, false)); } } } @@ -147,28 +109,24 @@ public class TestWebappClassLoader extends TomcatBaseTest { for (String prefix : prefixesPermit) { for (String suffix : classSuffixes) { name = prefix + "." + suffix; - Assert.assertTrue("Class '" + name + "' failed permit filter", - !loader.filter(name, true)); + Assert.assertTrue("Class '" + name + "' failed permit filter", !loader.filter(name, true)); } prefix = prefix.replace('.', '/'); for (String suffix : resourceSuffixes) { name = prefix + "/" + suffix; - Assert.assertTrue("Resource '" + name + "' failed permit filter", - !loader.filter(name, false)); + Assert.assertTrue("Resource '" + name + "' failed permit filter", !loader.filter(name, false)); } } for (String prefix : prefixesDeny) { for (String suffix : classSuffixes) { name = prefix + "." + suffix; - Assert.assertTrue("Class '" + name + "' failed deny filter", - loader.filter(name, true)); + Assert.assertTrue("Class '" + name + "' failed deny filter", loader.filter(name, true)); } prefix = prefix.replace('.', '/'); for (String suffix : resourceSuffixes) { name = prefix + "/" + suffix; - Assert.assertTrue("Resource '" + name + "' failed deny filter", - loader.filter(name, false)); + Assert.assertTrue("Resource '" + name + "' failed deny filter", loader.filter(name, false)); } } } diff --git a/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java b/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java index fc01786686..558513fd93 100644 --- a/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java +++ b/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java @@ -86,21 +86,17 @@ public class TestWebappClassLoaderExecutorMemoryLeak extends TomcatBaseTest { public transient volatile ThreadPoolExecutor tpe; @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.getWriter().println( - "The current thread served " + this + " servlet"); - tpe = new ThreadPoolExecutor(tpSize, tpSize, 50000L, - TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); + resp.getWriter().println("The current thread served " + this + " servlet"); + tpe = new ThreadPoolExecutor(tpSize, tpSize, 50000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); Task[] tasks = new Task[nTasks]; for (int i = 0; i < nTasks; i++) { tasks[i] = new Task("Task " + i); tpe.execute(tasks[i]); } - resp.getWriter().println("Started " + nTasks + - " never ending tasks using the ThreadPoolExecutor"); + resp.getWriter().println("Started " + nTasks + " never ending tasks using the ThreadPoolExecutor"); resp.getWriter().flush(); } diff --git a/test/org/apache/catalina/loader/TestWebappClassLoaderMemoryLeak.java b/test/org/apache/catalina/loader/TestWebappClassLoaderMemoryLeak.java index e9ccbd4356..70b069c340 100644 --- a/test/org/apache/catalina/loader/TestWebappClassLoaderMemoryLeak.java +++ b/test/org/apache/catalina/loader/TestWebappClassLoaderMemoryLeak.java @@ -59,8 +59,7 @@ public class TestWebappClassLoaderMemoryLeak extends TomcatBaseTest { Thread[] threads = getThreads(); for (Thread thread : threads) { - if (thread != null && thread.isAlive() && - TaskServlet.TIMER_THREAD_NAME.equals(thread.getName())) { + if (thread != null && thread.isAlive() && TaskServlet.TIMER_THREAD_NAME.equals(thread.getName())) { thread.join(5000); if (thread.isAlive()) { Assert.fail("Timer thread still running"); @@ -70,12 +69,11 @@ public class TestWebappClassLoaderMemoryLeak extends TomcatBaseTest { } /* - * Get the set of current threads as an array. - * Copied from WebappClassLoaderBase + * Get the set of current threads as an array. Copied from WebappClassLoaderBase */ private Thread[] getThreads() { // Get the current thread group - ThreadGroup tg = Thread.currentThread( ).getThreadGroup( ); + ThreadGroup tg = Thread.currentThread().getThreadGroup(); // Find the root thread group while (tg.getParent() != null) { tg = tg.getParent(); @@ -86,7 +84,7 @@ public class TestWebappClassLoaderMemoryLeak extends TomcatBaseTest { int threadCountActual = tg.enumerate(threads); // Make sure we don't miss any threads while (threadCountActual == threadCountGuess) { - threadCountGuess *=2; + threadCountGuess *= 2; threads = new Thread[threadCountGuess]; // Note tg.enumerate(Thread[]) silently ignores any threads that // can't fit into the array @@ -102,8 +100,7 @@ public class TestWebappClassLoaderMemoryLeak extends TomcatBaseTest { private static final String TIMER_THREAD_NAME = "leaked-thread"; @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Timer timer = new Timer(TIMER_THREAD_NAME); timer.schedule(new LocalTask(), 0, 10000); } diff --git a/test/org/apache/catalina/loader/TestWebappClassLoaderWeaving.java b/test/org/apache/catalina/loader/TestWebappClassLoaderWeaving.java index 1912264a50..5a808f9fb1 100644 --- a/test/org/apache/catalina/loader/TestWebappClassLoaderWeaving.java +++ b/test/org/apache/catalina/loader/TestWebappClassLoaderWeaving.java @@ -53,8 +53,7 @@ public class TestWebappClassLoaderWeaving extends TomcatBaseTest { copyResource(PACKAGE_PREFIX + "/TesterNeverWeavedClass.class", new File(classes, "TesterNeverWeavedClass.class")); - copyResource(PACKAGE_PREFIX + "/TesterUnweavedClass.class", - new File(classes, "TesterUnweavedClass.class")); + copyResource(PACKAGE_PREFIX + "/TesterUnweavedClass.class", new File(classes, "TesterUnweavedClass.class")); } @@ -269,11 +268,9 @@ public class TestWebappClassLoaderWeaving extends TomcatBaseTest { Boolean.valueOf(copiedLoader.getClearReferencesStopTimerThreads())); Assert.assertEquals("getContextName did not match.", this.loader.getContextName(), copiedLoader.getContextName()); - Assert.assertEquals("getDelegate did not match.", - Boolean.valueOf(this.loader.getDelegate()), + Assert.assertEquals("getDelegate did not match.", Boolean.valueOf(this.loader.getDelegate()), Boolean.valueOf(copiedLoader.getDelegate())); - Assert.assertEquals("getURLs did not match.", this.loader.getURLs().length, - copiedLoader.getURLs().length); + Assert.assertEquals("getURLs did not match.", this.loader.getURLs().length, copiedLoader.getURLs().length); Assert.assertSame("getParent did not match.", this.loader.getParent(), copiedLoader.getParent()); } @@ -293,8 +290,7 @@ public class TestWebappClassLoaderWeaving extends TomcatBaseTest { } } - private static String invokeDoMethodOnClass(WebappClassLoaderBase loader, String className) - throws Exception { + private static String invokeDoMethodOnClass(WebappClassLoaderBase loader, String className) throws Exception { Class<?> c = loader.findClass("org.apache.catalina.loader." + className); Assert.assertNotNull("The loaded class should not be null.", c); @@ -317,8 +313,7 @@ public class TestWebappClassLoaderWeaving extends TomcatBaseTest { } @Override - public byte[] transform(ClassLoader loader, String className, Class<?> x, - ProtectionDomain y, byte[] b) { + public byte[] transform(ClassLoader loader, String className, Class<?> x, ProtectionDomain y, byte[] b) { if (CLASS_TO_WEAVE.equals(className)) { return this.replacement; @@ -331,67 +326,55 @@ public class TestWebappClassLoaderWeaving extends TomcatBaseTest { } /** - * Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that - * the doMethod method returns "Hello, Weaver #1!". Compiled with Oracle Java 1.6.0_51. + * Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that the doMethod method returns + * "Hello, Weaver #1!". Compiled with Oracle Java 1.6.0_51. */ - private static final byte[] WEAVED_REPLACEMENT_1 = new byte[] { - -54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1, - 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 1, 0, - 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100, - 111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, - 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, - 105, 108, 101, 1, 0, 24, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, - 100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, 0, 5, 0, 6, 1, 0, 17, 72, 101, - 108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 49, 33, 1, 0, 46, 111, 114, - 103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108, - 111, 97, 100, 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, - 101, 100, 67, 108, 97, 115, 115, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, - 79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1, - 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, 0, 8, 0, 0, - 0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0, - 0, 3, 18, 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0, - 2, 0, 12 - }; + private static final byte[] WEAVED_REPLACEMENT_1 = new byte[] { -54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, + 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, + 111, 100, 101, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100, + 111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, + 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1, 0, 24, 84, 101, + 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, + 0, 5, 0, 6, 1, 0, 17, 72, 101, 108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 49, 33, 1, 0, 46, + 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108, 111, 97, 100, + 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 1, + 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, + 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, + 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0, 0, 3, 18, + 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0, 2, 0, 12 }; /** - * Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that - * the doMethod method returns "Hello, Weaver #2!". Compiled with Oracle Java 1.6.0_51. + * Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that the doMethod method returns + * "Hello, Weaver #2!". Compiled with Oracle Java 1.6.0_51. */ - private static final byte[] WEAVED_REPLACEMENT_2 = new byte[] { - -54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1, - 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 1, 0, - 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100, - 111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, - 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, - 105, 108, 101, 1, 0, 24, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, - 100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, 0, 5, 0, 6, 1, 0, 17, 72, 101, - 108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 50, 33, 1, 0, 46, 111, 114, - 103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108, - 111, 97, 100, 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, - 101, 100, 67, 108, 97, 115, 115, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, - 79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1, - 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, 0, 8, 0, 0, - 0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0, - 0, 3, 18, 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0, - 2, 0, 12 - }; + private static final byte[] WEAVED_REPLACEMENT_2 = new byte[] { -54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, + 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, + 111, 100, 101, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100, + 111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, + 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1, 0, 24, 84, 101, + 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, + 0, 5, 0, 6, 1, 0, 17, 72, 101, 108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 50, 33, 1, 0, 46, + 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108, 111, 97, 100, + 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 1, + 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, + 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, + 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0, 0, 3, 18, + 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0, 2, 0, 12 }; /* - * The WEAVED_REPLACEMENT_1 and WEAVED_REPLACEMENT_2 field contents are generated using the - * following code. To regenerate them, alter the TesterUnweavedClass code as desired, recompile, - * and run this main method. + * The WEAVED_REPLACEMENT_1 and WEAVED_REPLACEMENT_2 field contents are generated using the following code. To + * regenerate them, alter the TesterUnweavedClass code as desired, recompile, and run this main method. */ public static void main(String... arguments) throws Exception { ClassLoader cl = TestWebappClassLoaderWeaving.class.getClassLoader(); - try (InputStream input = cl.getResourceAsStream( - "org/apache/catalina/loader/TesterUnweavedClass.class")) { + try (InputStream input = cl.getResourceAsStream("org/apache/catalina/loader/TesterUnweavedClass.class")) { StringBuilder builder = new StringBuilder(); builder.append(" "); System.out.println(" private static final byte[] WEAVED_REPLACEMENT_1 = new byte[] {"); for (int i = 0, b = input.read(); b >= 0; i++, b = input.read()) { - String value = "" + ((byte)b); + String value = "" + ((byte) b); if (builder.length() + value.length() > 97) { builder.append(','); System.out.println(builder.toString()); diff --git a/test/org/apache/catalina/loader/TesterWebappClassLoaderThreadLocalMemoryLeak.java b/test/org/apache/catalina/loader/TesterWebappClassLoaderThreadLocalMemoryLeak.java index c833e1252f..b65e87fa26 100644 --- a/test/org/apache/catalina/loader/TesterWebappClassLoaderThreadLocalMemoryLeak.java +++ b/test/org/apache/catalina/loader/TesterWebappClassLoaderThreadLocalMemoryLeak.java @@ -55,14 +55,12 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest Tomcat tomcat = getTomcatInstance(); // Need to make sure we see a leak for the right reasons - tomcat.getServer().addLifecycleListener( - new JreMemoryLeakPreventionListener()); + tomcat.getServer().addLifecycleListener(new JreMemoryLeakPreventionListener()); // No file system docBase required Context ctx = getProgrammaticRootContext(); - Tomcat.addServlet(ctx, "leakServlet1", - "org.apache.tomcat.unittest.TesterLeakingServlet1"); + Tomcat.addServlet(ctx, "leakServlet1", "org.apache.tomcat.unittest.TesterLeakingServlet1"); ctx.addServletMappingDecoded("/leak1", "leakServlet1"); tomcat.start(); @@ -71,20 +69,17 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest ((ThreadPoolExecutor) executor).setThreadRenewalDelay(-1); // Configure logging filter to check leak message appears - TesterLogValidationFilter f = TesterLogValidationFilter.add(null, - "The web application [ROOT] created a ThreadLocal with key of", null, - "org.apache.catalina.loader.WebappClassLoaderBase"); + TesterLogValidationFilter f = + TesterLogValidationFilter.add(null, "The web application [ROOT] created a ThreadLocal with key of", + null, "org.apache.catalina.loader.WebappClassLoaderBase"); // Need to force loading of all web application classes via the web // application class loader - loadClass("TesterCounter", - (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); - loadClass("TesterLeakingServlet1", - (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); + loadClass("TesterCounter", (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); + loadClass("TesterLeakingServlet1", (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); // This will trigger the ThreadLocal creation - int rc = getUrl("http://localhost:" + getPort() + "/leak1", - new ByteChunk(), null); + int rc = getUrl("http://localhost:" + getPort() + "/leak1", new ByteChunk(), null); // Make sure request is OK Assert.assertEquals(HttpServletResponse.SC_OK, rc); @@ -95,8 +90,7 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest ctx = null; // Make sure we have a memory leak - String[] leaks = ((StandardHost) tomcat.getHost()) - .findReloadedContextMemoryLeaks(); + String[] leaks = ((StandardHost) tomcat.getHost()).findReloadedContextMemoryLeaks(); Assert.assertNotNull(leaks); Assert.assertTrue(leaks.length > 0); @@ -110,14 +104,12 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest Tomcat tomcat = getTomcatInstance(); // Need to make sure we see a leak for the right reasons - tomcat.getServer().addLifecycleListener( - new JreMemoryLeakPreventionListener()); + tomcat.getServer().addLifecycleListener(new JreMemoryLeakPreventionListener()); // No file system docBase required Context ctx = getProgrammaticRootContext(); - Tomcat.addServlet(ctx, "leakServlet2", - "org.apache.tomcat.unittest.TesterLeakingServlet2"); + Tomcat.addServlet(ctx, "leakServlet2", "org.apache.tomcat.unittest.TesterLeakingServlet2"); ctx.addServletMappingDecoded("/leak2", "leakServlet2"); tomcat.start(); @@ -126,22 +118,18 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest ((ThreadPoolExecutor) executor).setThreadRenewalDelay(-1); // Configure logging filter to check leak message appears - TesterLogValidationFilter f = TesterLogValidationFilter.add(null, - "The web application [ROOT] created a ThreadLocal with key of", null, - "org.apache.catalina.loader.WebappClassLoaderBase"); + TesterLogValidationFilter f = + TesterLogValidationFilter.add(null, "The web application [ROOT] created a ThreadLocal with key of", + null, "org.apache.catalina.loader.WebappClassLoaderBase"); // Need to force loading of all web application classes via the web // application class loader - loadClass("TesterCounter", - (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); - loadClass("TesterThreadScopedHolder", - (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); - loadClass("TesterLeakingServlet2", - (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); + loadClass("TesterCounter", (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); + loadClass("TesterThreadScopedHolder", (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); + loadClass("TesterLeakingServlet2", (WebappClassLoaderBase) ctx.getLoader().getClassLoader()); // This will trigger the ThreadLocal creation - int rc = getUrl("http://localhost:" + getPort() + "/leak2", - new ByteChunk(), null); + int rc = getUrl("http://localhost:" + getPort() + "/leak2", new ByteChunk(), null); // Make sure request is OK Assert.assertEquals(HttpServletResponse.SC_OK, rc); @@ -152,8 +140,7 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest ctx = null; // Make sure we have a memory leak - String[] leaks = ((StandardHost) tomcat.getHost()) - .findReloadedContextMemoryLeaks(); + String[] leaks = ((StandardHost) tomcat.getHost()).findReloadedContextMemoryLeaks(); Assert.assertNotNull(leaks); Assert.assertTrue(leaks.length > 0); @@ -163,23 +150,18 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest /** - * Utility method to ensure that classes are loaded by the - * WebappClassLoader. We can't just create classes since they will be loaded - * by the current class loader rather than the WebappClassLoader. This would - * mean that no leak occurred making the test for a leak rather pointless - * So, we load the bytes via the current class loader but define the class - * with the WebappClassLoader. - * - * This method assumes that all classes are in the current package. + * Utility method to ensure that classes are loaded by the WebappClassLoader. We can't just create classes since + * they will be loaded by the current class loader rather than the WebappClassLoader. This would mean that no leak + * occurred making the test for a leak rather pointless So, we load the bytes via the current class loader but + * define the class with the WebappClassLoader. This method assumes that all classes are in the current package. */ private void loadClass(String name, WebappClassLoaderBase cl) throws Exception { - try (InputStream is = cl.getResourceAsStream( - "org/apache/tomcat/unittest/" + name + ".class")) { + try (InputStream is = cl.getResourceAsStream("org/apache/tomcat/unittest/" + name + ".class")) { // We know roughly how big the class will be (~ 1K) so allow 2k as a // starting point byte[] classBytes = new byte[2048]; int offset = 0; - int read = is.read(classBytes, offset, classBytes.length-offset); + int read = is.read(classBytes, offset, classBytes.length - offset); while (read > -1) { offset += read; if (offset == classBytes.length) { @@ -188,11 +170,10 @@ public class TesterWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest System.arraycopy(classBytes, 0, tmp, 0, classBytes.length); classBytes = tmp; } - read = is.read(classBytes, offset, classBytes.length-offset); + read = is.read(classBytes, offset, classBytes.length - offset); } - Class<?> lpClass = cl.doDefineClass( - "org.apache.tomcat.unittest." + name, classBytes, 0, - offset, cl.getClass().getProtectionDomain()); + Class<?> lpClass = cl.doDefineClass("org.apache.tomcat.unittest." + name, classBytes, 0, offset, + cl.getClass().getProtectionDomain()); // Make sure we can create an instance lpClass.getConstructor().newInstance(); } diff --git a/test/org/apache/catalina/manager/TestHostManagerWebapp.java b/test/org/apache/catalina/manager/TestHostManagerWebapp.java index c62e575276..7d442fb2be 100644 --- a/test/org/apache/catalina/manager/TestHostManagerWebapp.java +++ b/test/org/apache/catalina/manager/TestHostManagerWebapp.java @@ -235,8 +235,7 @@ public class TestHostManagerWebapp extends TomcatBaseTest { Assert.assertTrue(serverXml.canRead()); addDeleteOnTearDown(serverXml); String serverXmlDump = ""; - try (FileReader reader = new FileReader(serverXml); - StringWriter writer = new StringWriter()) { + try (FileReader reader = new FileReader(serverXml); StringWriter writer = new StringWriter()) { IOTools.flow(reader, writer); serverXmlDump = writer.toString(); } diff --git a/test/org/apache/catalina/manager/TestManagerWebapp.java b/test/org/apache/catalina/manager/TestManagerWebapp.java index 388541e4ba..3b7846593e 100644 --- a/test/org/apache/catalina/manager/TestManagerWebapp.java +++ b/test/org/apache/catalina/manager/TestManagerWebapp.java @@ -45,17 +45,17 @@ import org.apache.catalina.util.URLEncoder; public class TestManagerWebapp extends TomcatBaseTest { - public static final String CONFIG = "<?xml version=\"1.0\" ?>" - + "<tomcat-users xmlns=\"http://tomcat.apache.org/xml\"" - + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" - + " xsi:schemaLocation=\"http://tomcat.apache.org/xml/tomcat-users.xsd\"" - + " version=\"1.0\">" - + "<role rolename=\"admin\" />" - + "<user username=\"admin\" password=\"sekr3t\" roles=\"manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script\" />" - + "</tomcat-users>"; + public static final String CONFIG = "<?xml version=\"1.0\" ?>" + + "<tomcat-users xmlns=\"http://tomcat.apache.org/xml\"" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xsi:schemaLocation=\"http://tomcat.apache.org/xml/tomcat-users.xsd\"" + " version=\"1.0\">" + + "<role rolename=\"admin\" />" + + "<user username=\"admin\" password=\"sekr3t\" roles=\"manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script\" />" + + "</tomcat-users>"; /** * Integration test for the manager webapp (verify all main Servlets are working). + * * @throws Exception if an error occurs */ @Test @@ -277,7 +277,7 @@ public class TestManagerWebapp extends TomcatBaseTest { // 10s default too low for some CI systems @Override public void connect() throws UnknownHostException, IOException { - connect(30000,30000); + connect(30000, 30000); } @Override @@ -398,8 +398,7 @@ public class TestManagerWebapp extends TomcatBaseTest { Assert.assertTrue(serverXml.canRead()); addDeleteOnTearDown(serverXml); String serverXmlDump = ""; - try (FileReader reader = new FileReader(serverXml); - StringWriter writer = new StringWriter()) { + try (FileReader reader = new FileReader(serverXml); StringWriter writer = new StringWriter()) { IOTools.flow(reader, writer); serverXmlDump = writer.toString(); } diff --git a/test/org/apache/catalina/manager/TestManagerWebappSsl.java b/test/org/apache/catalina/manager/TestManagerWebappSsl.java index 51caba7c04..5d990f8ac0 100644 --- a/test/org/apache/catalina/manager/TestManagerWebappSsl.java +++ b/test/org/apache/catalina/manager/TestManagerWebappSsl.java @@ -42,9 +42,8 @@ import org.apache.tomcat.util.net.TesterSupport; import org.apache.tomcat.websocket.server.WsContextListener; /** - * The keys and certificates used in this file are all available in svn and were - * generated using a test CA the files for which are in the Tomcat PMC private - * repository since not all of them are AL2 licensed. + * The keys and certificates used in this file are all available in svn and were generated using a test CA the files for + * which are in the Tomcat PMC private repository since not all of them are AL2 licensed. */ @RunWith(Parameterized.class) public class TestManagerWebappSsl extends TomcatBaseTest { @@ -52,12 +51,11 @@ public class TestManagerWebappSsl extends TomcatBaseTest { @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> parameters() { List<Object[]> parameterSets = new ArrayList<>(); - parameterSets.add(new Object[] { - "JSSE", Boolean.FALSE, "org.apache.tomcat.util.net.jsse.JSSEImplementation"}); - parameterSets.add(new Object[] { - "OpenSSL", Boolean.TRUE, "org.apache.tomcat.util.net.openssl.OpenSSLImplementation"}); - parameterSets.add(new Object[] { - "OpenSSL-FFM", Boolean.TRUE, "org.apache.tomcat.util.net.openssl.panama.OpenSSLImplementation"}); + parameterSets.add(new Object[] { "JSSE", Boolean.FALSE, "org.apache.tomcat.util.net.jsse.JSSEImplementation" }); + parameterSets.add( + new Object[] { "OpenSSL", Boolean.TRUE, "org.apache.tomcat.util.net.openssl.OpenSSLImplementation" }); + parameterSets.add(new Object[] { "OpenSSL-FFM", Boolean.TRUE, + "org.apache.tomcat.util.net.openssl.panama.OpenSSLImplementation" }); return parameterSets; } @@ -90,7 +88,7 @@ public class TestManagerWebappSsl extends TomcatBaseTest { tomcat.addWebapp(null, "/manager", appDir.getAbsolutePath()); appDir = new File(webappDir, "examples"); - Context ctxt = tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); + Context ctxt = tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); ctxt.addApplicationListener(WsContextListener.class.getName()); TesterSupport.initSsl(tomcat); @@ -98,8 +96,7 @@ public class TestManagerWebappSsl extends TomcatBaseTest { tomcat.start(); - ByteChunk res = getUrl("https://localhost:" + getPort() + - "/examples/servlets/servlet/HelloWorldExample"); + ByteChunk res = getUrl("https://localhost:" + getPort() + "/examples/servlets/servlet/HelloWorldExample"); Assert.assertTrue(res.toString().indexOf("<a href=\"../helloworld.html\">") > 0); // Add a regular connector diff --git a/test/org/apache/catalina/manager/TestStatusTransformer.java b/test/org/apache/catalina/manager/TestStatusTransformer.java index 0d9dbc8dfe..5dee74f796 100644 --- a/test/org/apache/catalina/manager/TestStatusTransformer.java +++ b/test/org/apache/catalina/manager/TestStatusTransformer.java @@ -38,7 +38,9 @@ import org.xml.sax.InputSource; public class TestStatusTransformer extends TomcatBaseTest { enum Mode { - HTML, XML, JSON + HTML, + XML, + JSON } @Test @@ -63,8 +65,7 @@ public class TestStatusTransformer extends TomcatBaseTest { File appDir = new File("test/webapp"); Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); ctxt.setPrivileged(true); - Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", - "org.apache.catalina.servlets.DefaultServlet"); + Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", "org.apache.catalina.servlets.DefaultServlet"); defaultServlet.addInitParameter("fileEncoding", "ISO-8859-1"); ctxt.addServletMappingDecoded("/", "default"); Tomcat.addServlet(ctxt, "status", "org.apache.catalina.manager.StatusManagerServlet"); @@ -121,8 +122,10 @@ public class TestStatusTransformer extends TomcatBaseTest { Assert.assertTrue(result.contains("name=localhost/")); } else if (mode.equals(Mode.XML)) { try (StringReader reader = new StringReader(body)) { - Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader)); - String serialized = ((DOMImplementationLS) xmlDocument.getImplementation()).createLSSerializer().writeToString(xmlDocument); + Document xmlDocument = + DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader)); + String serialized = ((DOMImplementationLS) xmlDocument.getImplementation()).createLSSerializer() + .writeToString(xmlDocument); // Verify that a request is being processed Assert.assertTrue(serialized.contains("stage=\"S\"")); } diff --git a/test/org/apache/catalina/mapper/TestMapper.java b/test/org/apache/catalina/mapper/TestMapper.java index 03386b18c6..589110e255 100644 --- a/test/org/apache/catalina/mapper/TestMapper.java +++ b/test/org/apache/catalina/mapper/TestMapper.java @@ -37,7 +37,7 @@ public class TestMapper extends LoggingBaseTest { protected Mapper mapper; - private HashMap<String, Host> hostMap = new HashMap<>(); + private HashMap<String,Host> hostMap = new HashMap<>(); private synchronized Host createHost(String name) { Host host = hostMap.get(name); @@ -524,16 +524,16 @@ public class TestMapper extends LoggingBaseTest { mapper.addContextVersion("aaaaaa", createHost("a6"), "", "0", createContext("c6"), new String[0], null, null); mapper.addContextVersion("aaaaaaa", createHost("a7"), "", "0", createContext("c7"), new String[0], null, null); - mapper.addWrappers("aaa", "", "0", Arrays.asList(new WrapperMappingInfo[] { - new WrapperMappingInfo("/", createWrapper("c3-default"), false, false) })); - mapper.addWrappers("aaaa", "", "0", Arrays.asList(new WrapperMappingInfo[] { - new WrapperMappingInfo("/", createWrapper("c4-default"), false, false) })); - mapper.addWrappers("aaaaa", "", "0", Arrays.asList(new WrapperMappingInfo[] { - new WrapperMappingInfo("/", createWrapper("c5-default"), false, false) })); - mapper.addWrappers("aaaaaa", "", "0", Arrays.asList(new WrapperMappingInfo[] { - new WrapperMappingInfo("/", createWrapper("c6-default"), false, false) })); - mapper.addWrappers("aaaaaaa", "", "0", Arrays.asList(new WrapperMappingInfo[] { - new WrapperMappingInfo("/", createWrapper("c7-default"), false, false) })); + mapper.addWrappers("aaa", "", "0", Arrays.asList( + new WrapperMappingInfo[] { new WrapperMappingInfo("/", createWrapper("c3-default"), false, false) })); + mapper.addWrappers("aaaa", "", "0", Arrays.asList( + new WrapperMappingInfo[] { new WrapperMappingInfo("/", createWrapper("c4-default"), false, false) })); + mapper.addWrappers("aaaaa", "", "0", Arrays.asList( + new WrapperMappingInfo[] { new WrapperMappingInfo("/", createWrapper("c5-default"), false, false) })); + mapper.addWrappers("aaaaaa", "", "0", Arrays.asList( + new WrapperMappingInfo[] { new WrapperMappingInfo("/", createWrapper("c6-default"), false, false) })); + mapper.addWrappers("aaaaaaa", "", "0", Arrays.asList( + new WrapperMappingInfo[] { new WrapperMappingInfo("/", createWrapper("c7-default"), false, false) })); MappingData mappingData = new MappingData(); MessageBytes hostMB = MessageBytes.newInstance(); diff --git a/test/org/apache/catalina/mbeans/TestRegistration.java b/test/org/apache/catalina/mbeans/TestRegistration.java index 9c46d4c7c1..e2c2462e25 100644 --- a/test/org/apache/catalina/mbeans/TestRegistration.java +++ b/test/org/apache/catalina/mbeans/TestRegistration.java @@ -41,9 +41,8 @@ import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.modeler.Registry; /** - * General tests around the process of registration and de-registration that - * don't necessarily apply to one specific Tomcat class. - * + * General tests around the process of registration and de-registration that don't necessarily apply to one specific + * Tomcat class. */ public class TestRegistration extends TomcatBaseTest { @@ -63,86 +62,58 @@ public class TestRegistration extends TomcatBaseTest { private static String[] basicMBeanNames() { - return new String[] { - "Tomcat:type=Engine", - "Tomcat:type=Realm,realmPath=/realm0", - "Tomcat:type=Mapper", - "Tomcat:type=MBeanFactory", - "Tomcat:type=NamingResources", - "Tomcat:type=Server", - "Tomcat:type=Service", - "Tomcat:type=StringCache", - "Tomcat:type=UtilityExecutor", - "Tomcat:type=Valve,name=StandardEngineValve", - }; + return new String[] { "Tomcat:type=Engine", "Tomcat:type=Realm,realmPath=/realm0", "Tomcat:type=Mapper", + "Tomcat:type=MBeanFactory", "Tomcat:type=NamingResources", "Tomcat:type=Server", "Tomcat:type=Service", + "Tomcat:type=StringCache", "Tomcat:type=UtilityExecutor", + "Tomcat:type=Valve,name=StandardEngineValve", }; } private static String[] hostMBeanNames(String host) { - return new String[] { - "Tomcat:type=Host,host=" + host, - "Tomcat:type=Valve,host=" + host + ",name=ErrorReportValve", - "Tomcat:type=Valve,host=" + host + ",name=StandardHostValve", - }; + return new String[] { "Tomcat:type=Host,host=" + host, + "Tomcat:type=Valve,host=" + host + ",name=ErrorReportValve", + "Tomcat:type=Valve,host=" + host + ",name=StandardHostValve", }; } private String[] optionalMBeanNames(String host) { if (isAccessLogEnabled()) { - return new String[] { - "Tomcat:type=Valve,host=" + host + ",name=AccessLogValve", - }; + return new String[] { "Tomcat:type=Valve,host=" + host + ",name=AccessLogValve", }; } else { - return new String[] { }; + return new String[] {}; } } private static String[] requestMBeanNames(String port, String type) { - return new String[] { - "Tomcat:type=RequestProcessor,worker=" + - ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port) + - ",name=HttpRequest1", - }; + return new String[] { "Tomcat:type=RequestProcessor,worker=" + + ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port) + ",name=HttpRequest1", }; } private static String[] contextMBeanNames(String host, String context) { return new String[] { - "Tomcat:j2eeType=WebModule,name=//" + host + context + - ",J2EEApplication=none,J2EEServer=none", - "Tomcat:type=Loader,host=" + host + ",context=" + context, - "Tomcat:type=Manager,host=" + host + ",context=" + context, - "Tomcat:type=NamingResources,host=" + host + ",context=" + context, - "Tomcat:type=Valve,host=" + host + ",context=" + context + - ",name=NonLoginAuthenticator", - "Tomcat:type=Valve,host=" + host + ",context=" + context + - ",name=StandardContextValve", - "Tomcat:type=ParallelWebappClassLoader,host=" + host + ",context=" + context, - "Tomcat:type=WebResourceRoot,host=" + host + ",context=" + context, - "Tomcat:type=WebResourceRoot,host=" + host + ",context=" + context + - ",name=Cache", - "Tomcat:type=Realm,realmPath=/realm0,host=" + host + - ",context=" + context, - "Tomcat:type=Realm,realmPath=/realm0/realm0,host=" + host + - ",context=" + context - }; + "Tomcat:j2eeType=WebModule,name=//" + host + context + ",J2EEApplication=none,J2EEServer=none", + "Tomcat:type=Loader,host=" + host + ",context=" + context, + "Tomcat:type=Manager,host=" + host + ",context=" + context, + "Tomcat:type=NamingResources,host=" + host + ",context=" + context, + "Tomcat:type=Valve,host=" + host + ",context=" + context + ",name=NonLoginAuthenticator", + "Tomcat:type=Valve,host=" + host + ",context=" + context + ",name=StandardContextValve", + "Tomcat:type=ParallelWebappClassLoader,host=" + host + ",context=" + context, + "Tomcat:type=WebResourceRoot,host=" + host + ",context=" + context, + "Tomcat:type=WebResourceRoot,host=" + host + ",context=" + context + ",name=Cache", + "Tomcat:type=Realm,realmPath=/realm0,host=" + host + ",context=" + context, + "Tomcat:type=Realm,realmPath=/realm0/realm0,host=" + host + ",context=" + context }; } private static String[] connectorMBeanNames(String port, String type) { - return new String[] { - "Tomcat:type=Connector,port=" + port + ",address=" - + ObjectName.quote(ADDRESS), - "Tomcat:type=GlobalRequestProcessor,name=" - + ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port), - "Tomcat:type=ProtocolHandler,port=" + port + ",address=" - + ObjectName.quote(ADDRESS), - "Tomcat:type=ThreadPool,name=" - + ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port), - "Tomcat:type=SocketProperties,name=" - + ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port), - }; + return new String[] { "Tomcat:type=Connector,port=" + port + ",address=" + ObjectName.quote(ADDRESS), + "Tomcat:type=GlobalRequestProcessor,name=" + + ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port), + "Tomcat:type=ProtocolHandler,port=" + port + ",address=" + ObjectName.quote(ADDRESS), + "Tomcat:type=ThreadPool,name=" + ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port), + "Tomcat:type=SocketProperties,name=" + ObjectName.quote("http-" + type + "-" + ADDRESS + "-" + port), }; } /* - * Test verifying that Tomcat correctly de-registers the MBeans it has - * registered. + * Test verifying that Tomcat correctly de-registers the MBeans it has registered. + * * @author Marc Guillemot */ @Test @@ -181,7 +152,7 @@ public class TestRegistration extends TomcatBaseTest { // Verify there are the correct Tomcat MBeans onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null); ArrayList<String> found = new ArrayList<>(onames.size()); - for (ObjectName on: onames) { + for (ObjectName on : onames) { found.add(on.toString()); } @@ -198,8 +169,7 @@ public class TestRegistration extends TomcatBaseTest { expected.addAll(Arrays.asList(contextMBeanNames("localhost", contextName))); expected.addAll(Arrays.asList(connectorMBeanNames("auto-" + index, protocol))); expected.addAll(Arrays.asList(optionalMBeanNames("localhost"))); - expected.addAll(Arrays.asList(requestMBeanNames( - "auto-" + index + "-" + getPort(), protocol))); + expected.addAll(Arrays.asList(requestMBeanNames("auto-" + index + "-" + getPort(), protocol))); // Did we find all expected MBeans? ArrayList<String> missing = new ArrayList<>(expected); @@ -248,8 +218,7 @@ public class TestRegistration extends TomcatBaseTest { } /* - * Confirm that, as far as ObjectName is concerned, the order of the key - * properties is not significant. + * Confirm that, as far as ObjectName is concerned, the order of the key properties is not significant. */ @Test public void testNames() throws MalformedObjectNameException { diff --git a/test/org/apache/catalina/nonblocking/TestNonBlockingAPI.java b/test/org/apache/catalina/nonblocking/TestNonBlockingAPI.java index 2d02de8493..59966836ad 100644 --- a/test/org/apache/catalina/nonblocking/TestNonBlockingAPI.java +++ b/test/org/apache/catalina/nonblocking/TestNonBlockingAPI.java @@ -78,7 +78,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { private static String TRAILER_HEADER_VALUE = "abcde"; private static final int CHUNK_SIZE = 1024 * 1024; - private static final int WRITE_SIZE = CHUNK_SIZE * 10; + private static final int WRITE_SIZE = CHUNK_SIZE * 10; private static final byte[] DATA = new byte[WRITE_SIZE]; private static final int WRITE_PAUSE_MS = 500; @@ -86,8 +86,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { static { // Use this sequence for padding to make it easier to spot errors - byte[] padding = new byte[] {'z', 'y', 'x', 'w', 'v', 'u', 't', 's', - 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k'}; + byte[] padding = new byte[] { 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k' }; int blockSize = padding.length; for (int i = 0; i < WRITE_SIZE / blockSize; i++) { @@ -96,8 +95,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { int padSize = blockSize - hexSize; System.arraycopy(padding, 0, DATA, i * blockSize, padSize); - System.arraycopy( - hex.getBytes(), 0, DATA, i * blockSize + padSize, hexSize); + System.arraycopy(hex.getBytes(), 0, DATA, i * blockSize + padSize, hexSize); } Field f = null; @@ -123,7 +121,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { } - @Test(expected=IOException.class) + @Test(expected = IOException.class) public void testNonBlockingReadIgnoreIsReady() throws Exception { doTestNonBlockingRead(true, false); } @@ -142,7 +140,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { tomcat.start(); - Map<String, List<String>> reqHeaders = new HashMap<>(); + Map<String,List<String>> reqHeaders = new HashMap<>(); int rc = postUrl(true, new DataWriter(async ? 0 : 500, async ? 2000000 : 5), "http://localhost:" + getPort() + "/", new ByteChunk(), reqHeaders, null); @@ -150,7 +148,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { if (async) { Assert.assertEquals(2000000 * 8, servlet.listener.body.length()); TestAsyncReadListener listener = (TestAsyncReadListener) servlet.listener; - Assert.assertTrue(Math.abs(listener.containerThreadCount.get() - listener.notReadyCount.get()) <= 1); + Assert.assertTrue(Math.abs(listener.containerThreadCount.get() - listener.notReadyCount.get()) <= 1); Assert.assertEquals(listener.isReadyCount.get(), listener.nonContainerThreadCount.get()); } else { Assert.assertEquals(5 * 8, servlet.listener.body.length()); @@ -650,8 +648,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { client.setPort(getPort()); client.setRequest(requestBody); /* - * Reduce default pause to speed up test execution. Pause only needs to be long enough that each part of the - * request is read separately. + * Reduce default pause to speed up test execution. Pause only needs to be long enough that each part of the + * request is read separately. */ client.setRequestPause(200); client.connect(); @@ -695,8 +693,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { Tomcat.addServlet(ctx, servletName, servlet); ctx.addServletMappingDecoded("/", servletName); // Note: Low values of socket.txBufSize can trigger very poor - // performance. Set it just low enough to ensure that the - // non-blocking write servlet will see isReady() == false + // performance. Set it just low enough to ensure that the + // non-blocking write servlet will see isReady() == false Assert.assertTrue(tomcat.getConnector().setProperty("socket.txBufSize", "1048576")); tomcat.start(); @@ -710,9 +708,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { OutputStream os = s.getOutputStream(); if (keepAlive) { - os.write(("OPTIONS * HTTP/1.1\r\n" + - "Host: localhost:" + getPort() + "\r\n" + - "\r\n").getBytes(StandardCharsets.ISO_8859_1)); + os.write(("OPTIONS * HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "\r\n") + .getBytes(StandardCharsets.ISO_8859_1)); os.flush(); // Make sure the entire response has been read. int read = is.read(buffer); @@ -722,10 +719,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { Assert.assertEquals(buffer[read - 2], '\r'); Assert.assertEquals(buffer[read - 1], '\n'); } - os.write(("GET / HTTP/1.1\r\n" + - "Host: localhost:" + getPort() + "\r\n" + - "Connection: close\r\n" + - "\r\n").getBytes(StandardCharsets.ISO_8859_1)); + os.write(("GET / HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "Connection: close\r\n" + "\r\n") + .getBytes(StandardCharsets.ISO_8859_1)); os.flush(); int read = 0; @@ -789,7 +784,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { // Read the chunk lineStart = lineEnd + 1; lineEnd = resultString.indexOf('\n', lineStart); - log.info("Start : " + lineStart + ", End: " + lineEnd); + log.info("Start : " + lineStart + ", End: " + lineEnd); if (lineEnd > lineStart) { line = resultString.substring(lineStart, lineEnd + 1); } else { @@ -801,8 +796,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { log.info(line); } if (chunkSize + 2 != line.length()) { - log.error("Chunk wrong length. Was " + line.length() + - " Expected " + (chunkSize + 2)); + log.error("Chunk wrong length. Was " + line.length() + " Expected " + (chunkSize + 2)); byte[] resultBytes = resultString.getBytes(); @@ -826,10 +820,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { if (resultEnd > resultString.length()) { resultEnd = resultString.length(); } - log.error("Mismatch tx: " + new String( - DATA, dataStart, dataEnd - dataStart)); - log.error("Mismatch rx: " + - resultString.substring(resultStart, resultEnd)); + log.error("Mismatch tx: " + new String(DATA, dataStart, dataEnd - dataStart)); + log.error("Mismatch rx: " + resultString.substring(resultStart, resultEnd)); found = true; break; } @@ -881,8 +873,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { Tomcat.addServlet(ctx, servletName, servlet); ctx.addServletMappingDecoded("/", servletName); // Note: Low values of socket.txBufSize can trigger very poor - // performance. Set it just low enough to ensure that the - // non-blocking write servlet will see isReady() == false + // performance. Set it just low enough to ensure that the + // non-blocking write servlet will see isReady() == false Assert.assertTrue(tomcat.getConnector().setProperty("socket.txBufSize", "524228")); tomcat.start(); @@ -891,10 +883,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { ByteChunk result = new ByteChunk(); OutputStream os = s.getOutputStream(); - os.write(("GET / HTTP/1.1\r\n" + - "Host: localhost:" + getPort() + "\r\n" + - "Connection: close\r\n" + - "\r\n").getBytes(StandardCharsets.ISO_8859_1)); + os.write(("GET / HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "Connection: close\r\n" + "\r\n") + .getBytes(StandardCharsets.ISO_8859_1)); os.flush(); InputStream is = s.getInputStream(); @@ -907,8 +897,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { long start = System.currentTimeMillis(); read = is.read(buffer); long end = System.currentTimeMillis(); - log.info("Client read [" + read + "] bytes in [" + (end - start) + - "] ms"); + log.info("Client read [" + read + "] bytes in [" + (end - start) + "] ms"); if (read > 0) { result.append(buffer, 0, read); } @@ -936,17 +925,17 @@ public class TestNonBlockingAPI extends TomcatBaseTest { int count = 0; while (count < 100 && !servlet.wlistener.onErrorInvoked) { Thread.sleep(100); - count ++; + count++; } while (count < 100 && !asyncContextIsComplete.get()) { Thread.sleep(100); - count ++; + count++; } while (count < 100 && alv.getEntryCount() < 1) { Thread.sleep(100); - count ++; + count++; } Assert.assertTrue("Error listener should have been invoked.", servlet.wlistener.onErrorInvoked); @@ -954,8 +943,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { // TODO Figure out why non-blocking writes with the NIO connector appear // to be slower on Linux - alv.validateAccessLog(1, 500, WRITE_PAUSE_MS, - WRITE_PAUSE_MS + 30 * 1000); + alv.validateAccessLog(1, 500, WRITE_PAUSE_MS, WRITE_PAUSE_MS + 30 * 1000); } @@ -973,7 +961,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { tomcat.start(); - Map<String, List<String>> resHeaders = new HashMap<>(); + Map<String,List<String>> resHeaders = new HashMap<>(); int rc = postUrl(false, new BytesStreamer() { @Override public byte[] next() { @@ -989,8 +977,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { public int available() { return 0; } - }, "http://localhost:" + - getPort() + "/", new ByteChunk(), resHeaders, null); + }, "http://localhost:" + getPort() + "/", new ByteChunk(), resHeaders, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); } @@ -1025,18 +1012,18 @@ public class TestNonBlockingAPI extends TomcatBaseTest { public byte[] next() { if (count < max) { if (count > 0) { - try { - if (delay > 0) { - Thread.sleep(delay); - } - } catch (Exception x) { - } + try { + if (delay > 0) { + Thread.sleep(delay); + } + } catch (Exception x) { + } } count++; if (count < max) { - return b; + return b; } else { - return f; + return f; } } else { return null; @@ -1114,7 +1101,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { } - public NBWriteServlet(AtomicBoolean asyncContextIsComplete, boolean unlimited, boolean listenerCompletesOnError) { + public NBWriteServlet(AtomicBoolean asyncContextIsComplete, boolean unlimited, + boolean listenerCompletesOnError) { this.asyncContextIsComplete = asyncContextIsComplete; this.unlimited = unlimited; this.listenerCompletesOnError = listenerCompletesOnError; @@ -1188,9 +1176,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { protected final StringBuilder body = new StringBuilder(); - TestReadListener(AsyncContext ctx, - boolean usingNonBlockingWrite, - boolean ignoreIsReady, + TestReadListener(AsyncContext ctx, boolean usingNonBlockingWrite, boolean ignoreIsReady, String expectedTrailerFieldValue) { this.ctx = ctx; this.usingNonBlockingWrite = usingNonBlockingWrite; @@ -1306,17 +1292,15 @@ public class TestNonBlockingAPI extends TomcatBaseTest { @Override public void onAllDataRead() { super.onAllDataRead(); - log.info("isReadyCount=" + isReadyCount + " notReadyCount=" + notReadyCount - + " containerThreadCount=" + containerThreadCount - + " nonContainerThreadCount=" + nonContainerThreadCount); + log.info("isReadyCount=" + isReadyCount + " notReadyCount=" + notReadyCount + " containerThreadCount=" + + containerThreadCount + " nonContainerThreadCount=" + nonContainerThreadCount); } @Override public void onError(Throwable throwable) { super.onError(throwable); - log.info("isReadyCount=" + isReadyCount + " notReadyCount=" + notReadyCount - + " containerThreadCount=" + containerThreadCount - + " nonContainerThreadCount=" + nonContainerThreadCount); + log.info("isReadyCount=" + isReadyCount + " notReadyCount=" + notReadyCount + " containerThreadCount=" + + containerThreadCount + " nonContainerThreadCount=" + nonContainerThreadCount); } } @@ -1335,10 +1319,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { public void onWritePossible() throws IOException { long start = System.currentTimeMillis(); int before = written; - while ((written < WRITE_SIZE || unlimited) && - ctx.getResponse().getOutputStream().isReady()) { - ctx.getResponse().getOutputStream().write( - DATA, written, CHUNK_SIZE); + while ((written < WRITE_SIZE || unlimited) && ctx.getResponse().getOutputStream().isReady()) { + ctx.getResponse().getOutputStream().write(DATA, written, CHUNK_SIZE); written += CHUNK_SIZE; } if (written == WRITE_SIZE) { @@ -1346,11 +1328,10 @@ public class TestNonBlockingAPI extends TomcatBaseTest { // calling complete ctx.getResponse().flushBuffer(); } - log.info("Write took: " + (System.currentTimeMillis() - start) + - " ms. Bytes before=" + before + " after=" + written); + log.info("Write took: " + (System.currentTimeMillis() - start) + " ms. Bytes before=" + before + " after=" + + written); // only call complete if we have emptied the buffer - if (ctx.getResponse().getOutputStream().isReady() && - written == WRITE_SIZE) { + if (ctx.getResponse().getOutputStream().isReady() && written == WRITE_SIZE) { // it is illegal to call complete // if there is a write in progress ctx.complete(); @@ -1423,14 +1404,14 @@ public class TestNonBlockingAPI extends TomcatBaseTest { } public static int postUrlWithDisconnect(boolean stream, BytesStreamer streamer, String path, - Map<String, List<String>> reqHead, Map<String, List<String>> resHead) throws IOException { + Map<String,List<String>> reqHead, Map<String,List<String>> resHead) throws IOException { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setReadTimeout(1000000); if (reqHead != null) { - for (Map.Entry<String, List<String>> entry : reqHead.entrySet()) { + for (Map.Entry<String,List<String>> entry : reqHead.entrySet()) { StringBuilder valueList = new StringBuilder(); for (String value : entry.getValue()) { if (valueList.length() > 0) { @@ -1462,7 +1443,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { int rc = connection.getResponseCode(); if (resHead != null) { - Map<String, List<String>> head = connection.getHeaderFields(); + Map<String,List<String>> head = connection.getHeaderFields(); resHead.putAll(head); } try { @@ -1494,14 +1475,13 @@ public class TestNonBlockingAPI extends TomcatBaseTest { CountDownLatch latch2 = new CountDownLatch(2); List<Throwable> exceptions = new ArrayList<>(); - Thread t = new Thread( - new RequestExecutor("http://localhost:" + getPort() + "/", latch2, exceptions)); + Thread t = new Thread(new RequestExecutor("http://localhost:" + getPort() + "/", latch2, exceptions)); t.start(); latch1.await(3000, TimeUnit.MILLISECONDS); - Thread t1 = new Thread(new RequestExecutor( - "http://localhost:" + getPort() + "/?notify=true", latch2, exceptions)); + Thread t1 = + new Thread(new RequestExecutor("http://localhost:" + getPort() + "/?notify=true", latch2, exceptions)); t1.start(); latch2.await(3000, TimeUnit.MILLISECONDS); @@ -1527,8 +1507,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { CountDownLatch latch2 = new CountDownLatch(1); List<Throwable> exceptions = new ArrayList<>(); - Thread t = new Thread( - new RequestPostExecutor("http://localhost:" + getPort() + "/", latch2, exceptions)); + Thread t = new Thread(new RequestPostExecutor("http://localhost:" + getPort() + "/", latch2, exceptions)); t.start(); latch1.await(3000, TimeUnit.MILLISECONDS); @@ -1637,11 +1616,11 @@ public class TestNonBlockingAPI extends TomcatBaseTest { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { final AsyncContext ctx = request.startAsync(); ctx.setTimeout(1000); - Thread readWriteListener = new Thread(new ReadWriteListener(latch, ctx)); + Thread readWriteListener = new Thread(new ReadWriteListener(latch, ctx)); readWriteListener.start(); } } @@ -1650,7 +1629,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { private final transient CountDownLatch latch; private final transient AsyncContext ctx; - ReadWriteListener(CountDownLatch latch, AsyncContext ctx){ + ReadWriteListener(CountDownLatch latch, AsyncContext ctx) { this.latch = latch; this.ctx = ctx; } @@ -1782,9 +1761,9 @@ public class TestNonBlockingAPI extends TomcatBaseTest { tomcat.start(); - Map<String, List<String>> resHeaders = new HashMap<>(); - int rc = postUrl(true, new DataWriter(500, 5), "http://localhost:" + - getPort() + "/", new ByteChunk(), resHeaders, null); + Map<String,List<String>> resHeaders = new HashMap<>(); + int rc = postUrl(true, new DataWriter(500, 5), "http://localhost:" + getPort() + "/", new ByteChunk(), + resHeaders, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); } @@ -1796,8 +1775,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { private static final long serialVersionUID = 1L; @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final CountDownLatch latch = new CountDownLatch(1); @@ -1878,21 +1856,14 @@ public class TestNonBlockingAPI extends TomcatBaseTest { /* - * Tests an error on an non-blocking read when the client closes the - * connection before fully writing the request body. + * Tests an error on an non-blocking read when the client closes the connection before fully writing the request + * body. * - * Required sequence is: - * - enter Servlet's service() method - * - startAsync() - * - configure non-blocking read - * - read partial body - * - close client connection - * - error is triggered - * - exit Servlet's service() method + * Required sequence is: - enter Servlet's service() method - startAsync() - configure non-blocking read - read + * partial body - close client connection - error is triggered - exit Servlet's service() method * - * This test makes extensive use of instance fields in the Servlet that - * would normally be considered very poor practice. It is only safe in this - * test as the Servlet only processes a single request. + * This test makes extensive use of instance fields in the Servlet that would normally be considered very poor + * practice. It is only safe in this test as the Servlet only processes a single request. */ private void doTestCanceledPost(String[] request) throws Exception { @@ -1955,8 +1926,7 @@ public class TestNonBlockingAPI extends TomcatBaseTest { } @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext ac = req.startAsync(); ac.setTimeout(-1); @@ -2029,9 +1999,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { } totalRead += bytesRead; isReady = sis.isReady(); - System.out.println("Read [" + bytesRead + - "], buffer [" + new String(buffer, 0, bytesRead, StandardCharsets.UTF_8) + - "], total read [" + totalRead + + System.out.println("Read [" + bytesRead + "], buffer [" + + new String(buffer, 0, bytesRead, StandardCharsets.UTF_8) + "], total read [" + totalRead + "], isReady [" + isReady + "]"); } while (isReady); if (totalRead == 16) { @@ -2067,12 +2036,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { /* - * Tests client disconnect in the following scenario: - * - async with non-blocking IO - * - response has been committed - * - no data in buffers - * - client disconnects - * - server attempts a write + * Tests client disconnect in the following scenario: - async with non-blocking IO - response has been committed - + * no data in buffers - client disconnects - server attempts a write */ private void doTestNonBlockingWriteError02(boolean swallowIoException) throws Exception { CountDownLatch responseCommitLatch = new CountDownLatch(1); @@ -2185,8 +2150,8 @@ public class TestNonBlockingAPI extends TomcatBaseTest { private final boolean swallowIoException; private volatile AtomicInteger stage = new AtomicInteger(0); - TestWriteListener02(AsyncContext ac, CountDownLatch responseCommitLatch, - CountDownLatch clientCloseLatch, boolean swallowIoException) { + TestWriteListener02(AsyncContext ac, CountDownLatch responseCommitLatch, CountDownLatch clientCloseLatch, + boolean swallowIoException) { this.ac = ac; this.responseCommitLatch = responseCommitLatch; this.clientCloseLatch = clientCloseLatch; diff --git a/test/org/apache/catalina/nonblocking/TesterAjpNonBlockingClient.java b/test/org/apache/catalina/nonblocking/TesterAjpNonBlockingClient.java index fce3a9ce77..f30deb4ebc 100644 --- a/test/org/apache/catalina/nonblocking/TesterAjpNonBlockingClient.java +++ b/test/org/apache/catalina/nonblocking/TesterAjpNonBlockingClient.java @@ -36,22 +36,19 @@ import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; /** - * This is not a standard set of unit tests. This is a set of test clients for - * AJP support of Servlet 3.1 non-blocking IO. It assumes that there is an httpd - * instance listening on localhost:80 that is redirecting all traffic to a - * default Tomcat instance of version 8 or above that includes the examples - * web application. + * This is not a standard set of unit tests. This is a set of test clients for AJP support of Servlet 3.1 non-blocking + * IO. It assumes that there is an httpd instance listening on localhost:80 that is redirecting all traffic to a default + * Tomcat instance of version 8 or above that includes the examples web application. */ public class TesterAjpNonBlockingClient extends TomcatBaseTest { @Test public void doTestAJPNonBlockingRead() throws Exception { - Map<String, List<String>> resHeaders = new HashMap<>(); + Map<String,List<String>> resHeaders = new HashMap<>(); ByteChunk out = new ByteChunk(); - int rc = postUrl(true, new DataWriter(2000, 5), "http://localhost" + - "/examples/servlets/nonblocking/bytecounter", - out, resHeaders, null); + int rc = postUrl(true, new DataWriter(2000, 5), + "http://localhost" + "/examples/servlets/nonblocking/bytecounter", out, resHeaders, null); System.out.println(out.toString()); @@ -67,10 +64,8 @@ public class TesterAjpNonBlockingClient extends TomcatBaseTest { ByteChunk result = new ByteChunk(); OutputStream os = s.getOutputStream(); - os.write(("GET /examples/servlets/nonblocking/numberwriter HTTP/1.1\r\n" + - "Host: localhost\r\n" + - "Connection: close\r\n" + - "\r\n").getBytes(StandardCharsets.ISO_8859_1)); + os.write(("GET /examples/servlets/nonblocking/numberwriter HTTP/1.1\r\n" + "Host: localhost\r\n" + + "Connection: close\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1)); os.flush(); InputStream is = s.getInputStream(); --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org