From f2c59a3cb781f3e9816e018c19351b1df876f97c Mon Sep 17 00:00:00 2001 From: Olivier Lamy Date: Thu, 23 May 2019 09:01:36 +1000 Subject: [PATCH 1/3] add convenient StringUtil isEmpty method (#3687) * add StringUtil.isEmpty Signed-off-by: olivier lamy --- .../jetty/client/HttpClientTLSTest.java | 3 +- .../jetty/client/HttpClientURITest.java | 3 +- .../fcgi/server/HttpChannelOverFCGI.java | 3 +- .../org/eclipse/jetty/http/HttpParser.java | 3 +- .../server/HTTP2ServerConnectionFactory.java | 3 +- .../jetty/util/StringIsEmptyBenchmark.java | 66 +++++++++++++++++++ .../jetty/server/session/SessionHandler.java | 2 +- .../org/eclipse/jetty/util/StringUtil.java | 25 ++++++- .../eclipse/jetty/util/StringUtilTest.java | 16 +++++ 9 files changed, 117 insertions(+), 7 deletions(-) create mode 100644 jetty-jmh/src/main/java/org/eclipse/jetty/util/StringIsEmptyBenchmark.java diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java index 959e9ac2639..8aebfe94044 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java @@ -45,6 +45,7 @@ import org.eclipse.jetty.io.ssl.SslHandshakeListener; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.ExecutorThreadPool; import org.eclipse.jetty.util.thread.QueuedThreadPool; @@ -501,7 +502,7 @@ public class HttpClientTLSTest while (true) { String line = reader.readLine(); - if (line == null || line.isEmpty()) + if (StringUtil.isEmpty(line)) break; } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java index c5a7158f96c..0863fcc770d 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java @@ -44,6 +44,7 @@ import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.Net; import org.eclipse.jetty.util.Fields; +import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.URIUtil; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.params.ParameterizedTest; @@ -609,7 +610,7 @@ public class HttpClientURITest extends AbstractHttpClientServerTest while (true) { String line = reader.readLine(); - if (line == null || line.isEmpty()) + if (StringUtil.isEmpty(line)) break; } diff --git a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java index db67c560a8d..1e75f083490 100644 --- a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java +++ b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/HttpChannelOverFCGI.java @@ -35,6 +35,7 @@ import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpChannel; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpTransport; +import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; @@ -87,7 +88,7 @@ public class HttpChannelOverFCGI extends HttpChannel public void onRequest() { String uri = path; - if (query != null && !query.isEmpty()) + if (!StringUtil.isEmpty(query)) uri += "?" + query; // TODO https? onRequest(new MetaData.Request(method, HttpScheme.HTTP.asString(), hostPort, uri, HttpVersion.fromString(version), fields,Long.MIN_VALUE)); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java index 13a807ce131..93efdc5dfa6 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java @@ -28,6 +28,7 @@ import org.eclipse.jetty.http.HttpTokens.EndOfContent; import org.eclipse.jetty.util.ArrayTernaryTrie; import org.eclipse.jetty.util.ArrayTrie; import org.eclipse.jetty.util.BufferUtil; +import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.Trie; import org.eclipse.jetty.util.Utf8StringBuilder; import org.eclipse.jetty.util.log.Log; @@ -1132,7 +1133,7 @@ public class HttpParser throw new BadMessageException(HttpStatus.BAD_REQUEST_400,"Header Folding"); // header value without name - continuation? - if (_valueString==null || _valueString.isEmpty()) + if ( StringUtil.isEmpty(_valueString)) { _string.setLength(0); _length=0; diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java index 9ae23123000..f2add0f087f 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.java @@ -38,6 +38,7 @@ import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.NegotiatingServerConnection.CipherDiscriminator; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; @@ -116,7 +117,7 @@ public class HTTP2ServerConnectionFactory extends AbstractHTTP2ServerConnectionF public void onClose(Session session, GoAwayFrame frame, Callback callback) { String reason = frame.tryConvertPayload(); - if (reason != null && !reason.isEmpty()) + if (!StringUtil.isEmpty(reason)) reason = " (" + reason + ")"; getConnection().onSessionFailure(new EofException(String.format("Close %s/%s", ErrorCode.toString(frame.getError(), null), reason)), callback); } diff --git a/jetty-jmh/src/main/java/org/eclipse/jetty/util/StringIsEmptyBenchmark.java b/jetty-jmh/src/main/java/org/eclipse/jetty/util/StringIsEmptyBenchmark.java new file mode 100644 index 00000000000..42e51760e8f --- /dev/null +++ b/jetty-jmh/src/main/java/org/eclipse/jetty/util/StringIsEmptyBenchmark.java @@ -0,0 +1,66 @@ +// +// ======================================================================== +// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.util; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +import java.util.concurrent.TimeUnit; + +@State( Scope.Benchmark) +@Threads(4) +@Warmup(iterations = 7, time = 500, timeUnit = TimeUnit.MILLISECONDS) +@Measurement(iterations = 9, time = 800, timeUnit = TimeUnit.MILLISECONDS) +public class StringIsEmptyBenchmark +{ + + private static final String SHORT = "beer.com/foo"; + + private static final String MEDIUM = "beer.com/foobarbeeerbe/bebbebbebebbe/bebbeghdegde/foobarbeeerbe/bebbebbebebbe/bebbeghdegde"; + + private static final String LONG = "beer.com/foobarbeeerbe/bebbebbebebbe/bebbeghdegde/foobarbeeerbe/bebbebbebebbe/bebbeghdegde/foobarbeeerbe/bebbebbebebbe/bebbeghdegde/foobarbeeerbe/bebbebbebebbe/bebbeghdegde/foobarbeeerbe/bebbebbebebbe/bebbeghdegde/foobarbeeerbe/bebbebbebebbe/bebbeghdegde/foobarbeeerbe/bebbebbebebbe/bebbeghdegde"; + + + @Benchmark + @BenchmarkMode( Mode.Throughput) + public void shortIsEmpty() + { + StringUtil.isEmpty(SHORT); + } + + @Benchmark + @BenchmarkMode( Mode.Throughput) + public void mediumIsEmpty() + { + StringUtil.isEmpty(MEDIUM); + } + + @Benchmark + @BenchmarkMode( Mode.Throughput) + public void longIsEmpty() + { + StringUtil.isEmpty(LONG); + } +} diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java index a3f74e63807..0165eda509c 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java @@ -725,7 +725,7 @@ public class SessionHandler extends ScopedHandler if (isUsingCookies()) { String sessionPath = (_cookieConfig.getPath()==null) ? contextPath : _cookieConfig.getPath(); - sessionPath = (sessionPath==null||sessionPath.isEmpty()) ? "/" : sessionPath; + sessionPath = (StringUtil.isEmpty(sessionPath)) ? "/" : sessionPath; String id = getExtendedId(session); HttpCookie cookie = null; if (_sessionComment == null) diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java index 60104d69f72..d32870b7df8 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java @@ -470,7 +470,30 @@ public class StringUtil // only whitespace return true; } - + + /** + *

Checks if a String is empty ("") or null.

+ * + *
+     *   isEmpty(null)   == true
+     *   isEmpty("")     == true
+     *   isEmpty("\r\n") == false
+     *   isEmpty("\t")   == false
+     *   isEmpty("   ")  == false
+     *   isEmpty("a")    == false
+     *   isEmpty(".")    == false
+     *   isEmpty(";\n")  == false
+     * 
+ * + * @param str + * the string to test. + * @return true if string is null or empty. + */ + public static boolean isEmpty(String str) + { + return str == null || str.isEmpty(); + } + /* ------------------------------------------------------------ */ /** * Test if a string is not null and contains at least 1 non-whitespace characters in it. diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/StringUtilTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/StringUtilTest.java index 8069b1fc595..51d53110410 100644 --- a/jetty-util/src/test/java/org/eclipse/jetty/util/StringUtilTest.java +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/StringUtilTest.java @@ -261,6 +261,22 @@ public class StringUtilTest assertTrue(StringUtil.isNotBlank(".")); assertTrue(StringUtil.isNotBlank(";\n")); } + + @Test + public void testIsEmpty() + { + assertTrue(StringUtil.isEmpty(null)); + assertTrue(StringUtil.isEmpty("")); + assertFalse(StringUtil.isEmpty("\r\n")); + assertFalse(StringUtil.isEmpty("\t")); + assertFalse(StringUtil.isEmpty(" ")); + + assertFalse(StringUtil.isEmpty("a")); + assertFalse(StringUtil.isEmpty(" a")); + assertFalse(StringUtil.isEmpty("a ")); + assertFalse(StringUtil.isEmpty(".")); + assertFalse(StringUtil.isEmpty(";\n")); + } @Test public void testSanitizeHTML() From 0ebc0fa9ce30bc6cd4bdeca7e95942b345a6c587 Mon Sep 17 00:00:00 2001 From: Olivier Lamy Date: Thu, 23 May 2019 14:12:44 +1000 Subject: [PATCH 2/3] Issue #3659 jmh tests are creating to many tmp files and never cleaned (#3650) * cleanup tmp files created by jmh tests Signed-off-by: olivier lamy --- Jmh_Jenkinsfile | 14 +++----- .../jetty/http/jmh/MultiPartBenchmark.java | 32 +++++++++++++------ .../jetty/server/jmh/ForwardBenchmark.java | 27 ++++------------ .../thread/strategy/jmh/EWYKBenchmark.java | 29 ++++++++++------- .../util/thread/strategy/jmh/TestServer.java | 3 +- 5 files changed, 52 insertions(+), 53 deletions(-) diff --git a/Jmh_Jenkinsfile b/Jmh_Jenkinsfile index 9c0a1d2fafe..a771e7594ac 100644 --- a/Jmh_Jenkinsfile +++ b/Jmh_Jenkinsfile @@ -4,20 +4,15 @@ def branch = params.get("JETTY_BRANCH" ,"jetty-9.4.x") def owner = params.get("REPO_OWNER", "eclipse") def jdk = params.get("JDK", "jdk8") def jmhJarPath = params.get("jmhJarPath","jetty-jmh/target/benchmarks.jar") +currentBuild.description = "Build branch $branch with jdk $jdk" node("linux") { // System Dependent Locations - def mvntool = tool name: 'maven3.5', type: 'hudson.tasks.Maven$MavenInstallation' - def jdktool = tool name: "$jdk", type: 'hudson.model.JDK' def mvnName = 'maven3.5' def localRepo = "${env.JENKINS_HOME}/${env.EXECUTOR_NUMBER}" def settingsName = 'oss-settings.xml' def mavenOpts = '-Xms1g -Xmx4g -Djava.awt.headless=true' - // Environment - List mvnEnv = ["PATH+MVN=${mvntool}/bin", "PATH+JDK=${jdktool}/bin", "JAVA_HOME=${jdktool}/", "MAVEN_HOME=${mvntool}"] - mvnEnv.add("MAVEN_OPTS=$mavenOpts") - stage("Checkout") { git url: "https://github.com/$owner/jetty.project.git", branch: "$branch" @@ -41,15 +36,14 @@ node("linux") { } // jmh run - -stage("jmh-run") { - node( 'jmh-build-node' ) { +node( 'jmh-build-node' ) { + stage("jmh-run") { timeout( time: 180, unit: 'MINUTES' ) { withEnv( ["JAVA_HOME=${tool "$jdk"}"] ) { unstash name: 'perf-tests' sh "rm -rf jmh_results" sh "mkdir jmh_results" - sh "${env.JAVA_HOME}/bin/java -jar $jmhJarPath -rff jmh_results/jmh_result.json -rf json" + sh "${env.JAVA_HOME}/bin/java -jar $jmhJarPath -rff jmh_results/jmh_result.json -rf json -foe true" jmhReport 'jmh_results/jmh_result.json' } } diff --git a/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java b/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java index 754d3cc6801..f2d62f8eb8b 100644 --- a/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java +++ b/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java @@ -26,7 +26,7 @@ import static org.hamcrest.Matchers.notNullValue; import org.eclipse.jetty.http.MultiPartFormInputStream; import org.eclipse.jetty.toolchain.test.Hex; -import org.eclipse.jetty.toolchain.test.IO; +import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.QuotedStringTokenizer; import org.eclipse.jetty.util.StringUtil; import org.hamcrest.Matchers; @@ -57,6 +57,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.security.DigestOutputStream; import java.security.MessageDigest; @@ -177,7 +178,7 @@ public class MultiPartBenchmark public long testLargeGenerated() throws Exception { Path multipartRawFile = _file.toPath(); - Path outputDir = new File("/tmp").toPath(); + Path outputDir = Files.createTempDirectory( "jetty_multipart_benchmark"); MultipartConfigElement config = newMultipartConfigElement(outputDir); @@ -188,11 +189,14 @@ public class MultiPartBenchmark case "HTTP": { MultiPartFormInputStream parser = new MultiPartFormInputStream(in, _contentType, config, outputDir.toFile()); + parser.setDeleteOnExit(true); if (parser.getParts().size() != _numSections) throw new IllegalStateException("Incorrect Parsing"); for (Part p : parser.getParts()) { count += p.getSize(); + if(p instanceof MultiPartFormInputStream.MultiPart) ((MultiPartFormInputStream.MultiPart)p).cleanUp(); + else p.delete(); } } break; @@ -200,11 +204,14 @@ public class MultiPartBenchmark case "UTIL": { org.eclipse.jetty.util.MultiPartInputStreamParser parser = new org.eclipse.jetty.util.MultiPartInputStreamParser(in, _contentType, config, outputDir.toFile()); + parser.setDeleteOnExit(true); if (parser.getParts().size() != _numSections) throw new IllegalStateException("Incorrect Parsing"); for (Part p : parser.getParts()) { count += p.getSize(); + if(p instanceof org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart) ((org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart)p).cleanUp(); + else p.delete(); } } break; @@ -213,7 +220,7 @@ public class MultiPartBenchmark throw new IllegalStateException("Unknown parserType Parameter"); } } - + IO.delete(outputDir.toFile()); return count; } @@ -236,18 +243,16 @@ public class MultiPartBenchmark { for (String multiPart : data) { - //Path multipartRawFile = MavenTestingUtils.getTestResourcePathFile("multipart/" + multiPart + ".raw"); String expectationPath = "multipart/" + multiPart + ".expected.txt"; - //Path expectationPath = MavenTestingUtils.getTestResourcePathFile("multipart/" + multiPart + ".expected.txt"); File expectationFile = File.createTempFile( expectationPath, ".tmp" ); - try(InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(expectationPath); - OutputStream os = Files.newOutputStream( expectationFile.toPath() )) { - IO.copy( inputStream, os ); + try(InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(expectationPath); // + OutputStream os = Files.newOutputStream( expectationFile.toPath())) { + IO.copy(inputStream, os); } - Path outputDir = Files.createTempDirectory( "expected_output_jmh_jetty" );// new File("/tmp").toPath(); + Path outputDir = Files.createTempDirectory("expected_output_jmh_jetty"); MultipartExpectations multipartExpectations = new MultipartExpectations(expectationFile.toPath()); MultipartConfigElement config = newMultipartConfigElement(outputDir); @@ -259,18 +264,24 @@ public class MultiPartBenchmark case "HTTP": { MultiPartFormInputStream parser = new MultiPartFormInputStream(in, multipartExpectations.contentType, config, outputDir.toFile()); + parser.setDeleteOnExit(true); for (Part p : parser.getParts()) { count += p.getSize(); + if(p instanceof MultiPartFormInputStream.MultiPart) ((MultiPartFormInputStream.MultiPart)p).cleanUp(); + else p.delete(); } } break; case "UTIL": { org.eclipse.jetty.util.MultiPartInputStreamParser parser = new org.eclipse.jetty.util.MultiPartInputStreamParser(in, multipartExpectations.contentType, config, outputDir.toFile()); + parser.setDeleteOnExit(true); for (Part p : parser.getParts()) { count += p.getSize(); + if(p instanceof org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart) ((org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart)p).cleanUp(); + else p.delete(); } } break; @@ -278,7 +289,8 @@ public class MultiPartBenchmark throw new IllegalStateException("Unknown parserType Parameter"); } } - + Files.deleteIfExists(expectationFile.toPath()); + IO.delete(outputDir.toFile()); } return count; } diff --git a/jetty-jmh/src/main/java/org/eclipse/jetty/server/jmh/ForwardBenchmark.java b/jetty-jmh/src/main/java/org/eclipse/jetty/server/jmh/ForwardBenchmark.java index 20660748b67..2f77f105103 100644 --- a/jetty-jmh/src/main/java/org/eclipse/jetty/server/jmh/ForwardBenchmark.java +++ b/jetty-jmh/src/main/java/org/eclipse/jetty/server/jmh/ForwardBenchmark.java @@ -18,28 +18,9 @@ package org.eclipse.jetty.server.jmh; -import java.io.IOException; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.util.Arrays; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.server.ForwardedRequestCustomizer; -import org.eclipse.jetty.server.HttpConfiguration; -import org.eclipse.jetty.server.HttpConnectionFactory; -import org.eclipse.jetty.server.LocalConnector; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.ArrayTrie; import org.eclipse.jetty.util.Trie; import org.openjdk.jmh.annotations.Benchmark; @@ -56,8 +37,12 @@ import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; -import static java.lang.invoke.MethodHandles.dropArguments; -import static java.lang.invoke.MethodHandles.foldArguments; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + import static java.lang.invoke.MethodType.methodType; diff --git a/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/EWYKBenchmark.java b/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/EWYKBenchmark.java index 7c81298cc83..2292281ede2 100644 --- a/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/EWYKBenchmark.java +++ b/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/EWYKBenchmark.java @@ -19,11 +19,16 @@ package org.eclipse.jetty.util.thread.strategy.jmh; import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; +import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.util.thread.ExecutionStrategy; import org.eclipse.jetty.util.thread.Invocable; @@ -51,7 +56,7 @@ public class EWYKBenchmark { static TestServer server; static ReservedThreadExecutor reserved; - static File directory; + static Path directory; @Param({"PC","PEC","EWYK"}) public static String strategyName; @@ -66,21 +71,15 @@ public class EWYKBenchmark public static void setupServer() throws Exception { // Make a test directory - directory = File.createTempFile("ewyk","dir"); - if (directory.exists()) - directory.delete(); - directory.mkdir(); - directory.deleteOnExit(); - + directory = Files.createTempDirectory("ewyk"); + // Make some test files for (int i=0;i<75;i++) { - File file =new File(directory,i+".txt"); - file.createNewFile(); - file.deleteOnExit(); + File.createTempFile( "ewyk_benchmark", i + ".txt" , directory.toFile()); } - server=new TestServer(directory); + server=new TestServer(directory.toFile()); server.start(); reserved = new ReservedThreadExecutor(server,20); reserved.start(); @@ -89,6 +88,14 @@ public class EWYKBenchmark @TearDown(Level.Trial) public static void stopServer() throws Exception { + try + { + IO.delete(directory.toFile()); + } + catch ( Exception e ) + { + System.out.println("cannot delete directory:"+directory); + } reserved.stop(); server.stop(); } diff --git a/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/TestServer.java b/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/TestServer.java index ab99582cad6..3f05463f2ab 100644 --- a/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/TestServer.java +++ b/jetty-jmh/src/main/java/org/eclipse/jetty/util/thread/strategy/jmh/TestServer.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.util.thread.strategy.jmh; import java.io.File; +import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -44,7 +45,7 @@ public class TestServer implements Executor, TryExecutor TestServer() { - this(new File("/tmp/")); + this(new File(System.getProperty("java.io.tmpdir"))); } From a3b755858d6b370bb280063af4442e5763601741 Mon Sep 17 00:00:00 2001 From: Michael Hausegger Date: Fri, 24 May 2019 08:24:40 +0200 Subject: [PATCH 3/3] Added additional Unit Tests to increase code coverage (#3692) * Added additional Unit Tests to increase code coverage Signed-off-by: Michael Hausegger --- .../org/eclipse/jetty/util/ArrayUtilTest.java | 103 ++++++++++++++++++ .../jetty/util/IntrospectionUtilTest.java | 76 +++++++++++++ .../org/eclipse/jetty/util/LoaderTest.java | 55 ++++++++++ 3 files changed, 234 insertions(+) create mode 100644 jetty-util/src/test/java/org/eclipse/jetty/util/ArrayUtilTest.java create mode 100644 jetty-util/src/test/java/org/eclipse/jetty/util/IntrospectionUtilTest.java create mode 100644 jetty-util/src/test/java/org/eclipse/jetty/util/LoaderTest.java diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/ArrayUtilTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/ArrayUtilTest.java new file mode 100644 index 00000000000..b27d46ac17d --- /dev/null +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/ArrayUtilTest.java @@ -0,0 +1,103 @@ +// +// ======================================================================== +// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.util; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Unit tests for class {@link ArrayUtil}. + * + * @see ArrayUtil + */ +public class ArrayUtilTest +{ + + @Test + public void testAddToArrayWithEmptyArray() + { + String[] stringArray = new String[0]; + String[] resultArray = ArrayUtil.addToArray(stringArray, "Ca?", Object.class); + + assertEquals(0, stringArray.length); + assertEquals(1, resultArray.length); + + assertNotSame(stringArray, resultArray); + assertNotSame(resultArray, stringArray); + + assertFalse(resultArray.equals(stringArray)); + assertEquals(String.class, resultArray[0].getClass()); + } + + @Test + public void testAddUsingNull() + { + String[] stringArray = new String[7]; + String[] stringArrayTwo = ArrayUtil.add(stringArray, null); + + assertEquals(7, stringArray.length); + assertEquals(7, stringArrayTwo.length); + + assertSame(stringArray, stringArrayTwo); + assertSame(stringArrayTwo, stringArray); + } + + @Test + public void testAddWithNonEmptyArray() + { + Object[] objectArray = new Object[3]; + Object[] objectArrayTwo = ArrayUtil.add(objectArray, objectArray); + + assertEquals(3, objectArray.length); + assertEquals(6, objectArrayTwo.length); + + assertNotSame(objectArray, objectArrayTwo); + assertNotSame(objectArrayTwo, objectArray); + + assertFalse(objectArrayTwo.equals(objectArray)); + } + + @Test + public void testRemoveFromNullArrayReturningNull() + { + assertNull(ArrayUtil.removeFromArray((Integer[])null, new Object())); + } + + @Test + public void testRemoveNulls() + { + Object[] objectArray = new Object[2]; + objectArray[0] = new Object(); + Object[] resultArray = ArrayUtil.removeNulls(objectArray); + + assertEquals(2, objectArray.length); + assertEquals(1, resultArray.length); + + assertNotSame(objectArray, resultArray); + assertNotSame(resultArray, objectArray); + + assertFalse(resultArray.equals(objectArray)); + } + +} diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/IntrospectionUtilTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/IntrospectionUtilTest.java new file mode 100644 index 00000000000..40d8c2d91a6 --- /dev/null +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/IntrospectionUtilTest.java @@ -0,0 +1,76 @@ +// +// ======================================================================== +// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.util; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Array; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit tests for class {@link IntrospectionUtil}. + * + * @see IntrospectionUtil + */ +public class IntrospectionUtilTest +{ + + @Test + public void testIsTypeCompatibleWithTwoTimesString() + { + assertTrue(IntrospectionUtil.isTypeCompatible(String.class, String.class, true)); + } + + @Test + public void testIsSameSignatureWithNull() + { + assertFalse(IntrospectionUtil.isSameSignature(null, null)); + } + + @Test + public void testFindMethodWithEmptyString() + { + assertThrows(NoSuchMethodException.class, + () -> IntrospectionUtil.findMethod(Integer.class, "", null, false, false)); + } + + @Test + public void testFindMethodWithNullMethodParameter() + { + assertThrows(NoSuchMethodException.class, + () -> IntrospectionUtil.findMethod(String.class, null, (Class[])Array.newInstance(Class.class, 3), true, true)); + } + + @Test + public void testFindMethodWithNullClassParameter() throws NoSuchMethodException + { + assertThrows(NoSuchMethodException.class, + () -> IntrospectionUtil.findMethod(null, "subSequence", (Class[])Array.newInstance(Class.class, 9), false, false)); + } + + @Test + public void testIsJavaBeanCompliantSetterWithNull() + { + assertFalse(IntrospectionUtil.isJavaBeanCompliantSetter(null)); + } + +} diff --git a/jetty-util/src/test/java/org/eclipse/jetty/util/LoaderTest.java b/jetty-util/src/test/java/org/eclipse/jetty/util/LoaderTest.java new file mode 100644 index 00000000000..cec85d6d1b4 --- /dev/null +++ b/jetty-util/src/test/java/org/eclipse/jetty/util/LoaderTest.java @@ -0,0 +1,55 @@ +// +// ======================================================================== +// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.util; + +import org.junit.jupiter.api.Test; + +import java.util.Locale; +import java.util.MissingResourceException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Unit tests for class {@link Loader}. + * + * @see Loader + */ +public class LoaderTest +{ + + @Test + public void testGetResourceBundleThrowsMissingResourceException() + { + assertThrows(MissingResourceException.class, () -> Loader.getResourceBundle("nothing", true, Locale.ITALIAN)); + } + + @Test + public void testLoadClassThrowsClassNotFoundException() + { + assertThrows(ClassNotFoundException.class, () -> Loader.loadClass(Object.class, "String")); + } + + @Test + public void testLoadClassSucceeds() throws ClassNotFoundException + { + assertEquals(LazyList.class, Loader.loadClass(Object.class, "org.eclipse.jetty.util.LazyList")); + } + +}