diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index a6a33c6f800e..26d39ea2e7f8 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -47,7 +47,6 @@ import java.security.KeyPair; import java.security.SecureRandom; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; @@ -267,7 +266,7 @@ public boolean verify(String s, SSLSession sslSession) { } if (args.isEmpty()) - args = Collections.singletonList("help"); // default to help + args = List.of("help"); // default to help if (mode == null) { mode = Mode.HTTP; @@ -346,7 +345,7 @@ class Authenticator extends ClientEndpointConfig.Configurator { @Override public void beforeRequest(Map> headers) { if (factory.authorization != null) { - headers.put("Authorization", Collections.singletonList(factory.authorization)); + headers.put("Authorization", List.of(factory.authorization)); } } } diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 5badd296fbf0..3d6ea7c42530 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -35,7 +35,6 @@ import java.net.URLConnection; import java.security.KeyPair; import java.security.PublicKey; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Level; @@ -114,7 +113,7 @@ public boolean verifyServerKey(ClientSession clientSession, SocketAddress remote WaitableFuture wf = channel.open(); wf.await(); - Set waitMask = channel.waitFor(Collections.singletonList(ClientChannelEvent.CLOSED), 0L); + Set waitMask = channel.waitFor(List.of(ClientChannelEvent.CLOSED), 0L); if (waitMask.contains(ClientChannelEvent.TIMEOUT)) { throw new SocketTimeoutException("Failed to retrieve command result in time: " + command); diff --git a/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java b/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java index 98a4fefd8001..fb816f012018 100644 --- a/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java +++ b/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java @@ -157,9 +157,9 @@ void newop() throws IOException { while (server.stdin.size() == 0) { Thread.sleep(100); } - assertEquals("hello", server.stdin.toString(Charset.defaultCharset().name())); + assertEquals("hello", server.stdin.toString(Charset.defaultCharset())); assertEquals("command", server.arg); - assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset().name())); + assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset())); assertEquals(2, client.code); } diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java index 13976387db19..61f7a0560483 100644 --- a/core/src/main/java/hudson/ClassicPluginStrategy.java +++ b/core/src/main/java/hudson/ClassicPluginStrategy.java @@ -50,6 +50,7 @@ import java.util.Enumeration; import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; @@ -338,7 +339,7 @@ public List> findComponents(Class type, Hudson huds List finders; if (type == ExtensionFinder.class) { // Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders - finders = Collections.singletonList(new ExtensionFinder.Sezpoz()); + finders = List.of(new ExtensionFinder.Sezpoz()); } else { finders = hudson.getExtensionList(ExtensionFinder.class); } @@ -597,7 +598,7 @@ static final class DependencyClassLoader extends ClassLoader { DependencyClassLoader(ClassLoader parent, File archive, List dependencies, PluginManager pluginManager) { super(parent); this._for = archive; - this.dependencies = Collections.unmodifiableList(new ArrayList<>(dependencies)); + this.dependencies = List.copyOf(dependencies); this.pluginManager = pluginManager; } @@ -629,7 +630,7 @@ protected List getEdges(PluginWrapper pw) { for (Dependency d : dependencies) { PluginWrapper p = pluginManager.getPlugin(d.shortName); if (p != null && p.isActive()) - cgd.run(Collections.singleton(p)); + cgd.run(Set.of(p)); } } catch (CycleDetectedException e) { throw new AssertionError(e); // such error should have been reported earlier diff --git a/core/src/main/java/hudson/ExtensionFinder.java b/core/src/main/java/hudson/ExtensionFinder.java index 5bddd008f5f0..5c2efcb1c805 100644 --- a/core/src/main/java/hudson/ExtensionFinder.java +++ b/core/src/main/java/hudson/ExtensionFinder.java @@ -560,7 +560,7 @@ protected void configure() { } public List> getLoadedIndex() { - return Collections.unmodifiableList(new ArrayList<>(loadedIndex)); + return List.copyOf(loadedIndex); } @Override @@ -645,7 +645,7 @@ private List> getIndices() { // 5. dead lock if (indices == null) { ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader; - indices = Collections.unmodifiableList(StreamSupport.stream(Index.load(Extension.class, Object.class, cl).spliterator(), false).collect(Collectors.toList())); + indices = StreamSupport.stream(Index.load(Extension.class, Object.class, cl).spliterator(), false).collect(Collectors.toUnmodifiableList()); } return indices; } diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index 6b22e21d8362..3b4f9b65de98 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -2382,7 +2382,7 @@ private static class ReadToString extends MasterToSlaveFileCallable { @Override public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { - return new String(Files.readAllBytes(fileToPath(f)), Charset.defaultCharset()); + return Files.readString(fileToPath(f), Charset.defaultCharset()); } } diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 49af99f61849..66d67248fcac 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -100,7 +100,6 @@ import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; -import java.io.UnsupportedEncodingException; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; @@ -747,10 +746,7 @@ public static String appendSpaceIfNotNull(String n) { public static String nbspIndent(String size) { int i = size.indexOf('x'); i = Integer.parseInt(i > 0 ? size.substring(0, i) : size) / 10; - StringBuilder buf = new StringBuilder(30); - for (int j = 2; j <= i; j++) - buf.append(" "); - return buf.toString(); + return " ".repeat(Math.max(0, i - 1)); } public static String getWin32ErrorMessage(IOException e) { @@ -777,11 +773,7 @@ public static String urlEncode(String s) { if (s == null) { return ""; } - try { - return URLEncoder.encode(s, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new Error(e); // impossible - } + return URLEncoder.encode(s, StandardCharsets.UTF_8); } public static String escape(String s) { @@ -1933,11 +1925,11 @@ public void calcCheckUrl(Map attributes, String userDefined, Object descriptor, * * Used in {@code task.jelly} to decide if the page should be highlighted. */ - public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException { + public boolean hyperlinkMatchesCurrentPage(String href) { String url = Stapler.getCurrentRequest().getRequestURL().toString(); if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/"); - url = URLDecoder.decode(url, "UTF-8"); - href = URLDecoder.decode(href, "UTF-8"); + url = URLDecoder.decode(url, StandardCharsets.UTF_8); + href = URLDecoder.decode(href, StandardCharsets.UTF_8); if (url.endsWith("/")) url = url.substring(0, url.length() - 1); if (href.endsWith("/")) href = href.substring(0, href.length() - 1); @@ -1945,7 +1937,7 @@ public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodi } public List singletonList(T t) { - return Collections.singletonList(t); + return List.of(t); } /** diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index 6114152522d6..568ad7df43d6 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -930,7 +930,7 @@ public void dynamicLoad(File arc, boolean removeExisting, @CheckForNull List, ModelObject { private final List optionalDependencies; public List getDependencyErrors() { - return Collections.unmodifiableList(new ArrayList<>(dependencyErrors.keySet())); + return List.copyOf(dependencyErrors.keySet()); } @Restricted(NoExternalUse.class) // Jelly use @@ -222,7 +222,7 @@ public boolean hasDerivedDependencyErrors() { * The core can depend on a plugin if it is bundled. Sometimes it's the only thing that * depends on the plugin e.g. UI support library bundle plugin. */ - private static Set CORE_ONLY_DEPENDANT = Collections.singleton("jenkins-core"); + private static Set CORE_ONLY_DEPENDANT = Set.of("jenkins-core"); /** * Set the list of components that depend on this plugin. diff --git a/core/src/main/java/hudson/StructuredForm.java b/core/src/main/java/hudson/StructuredForm.java index 708d0120dc9d..600da990aefb 100644 --- a/core/src/main/java/hudson/StructuredForm.java +++ b/core/src/main/java/hudson/StructuredForm.java @@ -67,7 +67,7 @@ public static List toList(JSONObject parent, String propertyName) { if (v == null) return Collections.emptyList(); if (v instanceof JSONObject) - return Collections.singletonList((JSONObject) v); + return List.of((JSONObject) v); if (v instanceof JSONArray) return (List) v; diff --git a/core/src/main/java/hudson/WebAppMain.java b/core/src/main/java/hudson/WebAppMain.java index c63e1f813a96..9327d78568a5 100644 --- a/core/src/main/java/hudson/WebAppMain.java +++ b/core/src/main/java/hudson/WebAppMain.java @@ -140,7 +140,7 @@ public void contextInitialized(ServletContextEvent event) { // Nicer console log formatting when using mvn jetty:run. if (Main.isDevelopmentMode && System.getProperty("java.util.logging.config.file") == null) { try { - Formatter formatter = (Formatter) Class.forName("io.jenkins.lib.support_log_formatter.SupportLogFormatter").newInstance(); + Formatter formatter = (Formatter) Class.forName("io.jenkins.lib.support_log_formatter.SupportLogFormatter").getDeclaredConstructor().newInstance(); for (Handler h : Logger.getLogger("").getHandlers()) { if (h instanceof ConsoleHandler) { ((ConsoleHandler) h).setFormatter(formatter); diff --git a/core/src/main/java/hudson/cli/CLIAction.java b/core/src/main/java/hudson/cli/CLIAction.java index 31d4700e4cb1..633ecca3437c 100644 --- a/core/src/main/java/hudson/cli/CLIAction.java +++ b/core/src/main/java/hudson/cli/CLIAction.java @@ -277,8 +277,8 @@ void run() throws IOException, InterruptedException { wait(); } } - PrintStream stdout = new PrintStream(streamStdout(), false, encoding.name()); - PrintStream stderr = new PrintStream(streamStderr(), true, encoding.name()); + PrintStream stdout = new PrintStream(streamStdout(), false, encoding); + PrintStream stderr = new PrintStream(streamStderr(), true, encoding); if (args.isEmpty()) { stderr.println("Connection closed before arguments received"); sendExit(2); diff --git a/core/src/main/java/hudson/cli/CLICommand.java b/core/src/main/java/hudson/cli/CLICommand.java index ab0a7266aec1..e779afbc3453 100644 --- a/core/src/main/java/hudson/cli/CLICommand.java +++ b/core/src/main/java/hudson/cli/CLICommand.java @@ -42,7 +42,6 @@ import java.io.InputStream; import java.io.PrintStream; import java.io.UncheckedIOException; -import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.nio.charset.Charset; @@ -415,11 +414,7 @@ public final String getSingleLineSummary() { } catch (InterruptedException e) { throw new RuntimeException(e); } - try { - return out.toString(charset.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return out.toString(charset); } /** @@ -437,11 +432,7 @@ public final String getUsage() { } catch (InterruptedException e) { throw new RuntimeException(e); } - try { - return out.toString(charset.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return out.toString(charset); } /** @@ -458,20 +449,11 @@ public final String getLongDescription() { } catch (InterruptedException e) { throw new RuntimeException(e); } - PrintStream ps; - try { - ps = new PrintStream(out, false, charset.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + PrintStream ps = new PrintStream(out, false, charset); printUsageSummary(ps); ps.close(); - try { - return out.toString(charset.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return out.toString(charset); } /** diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index 0bd6947270f0..f147cdb87975 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -925,7 +925,7 @@ public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOEx @Override @NonNull public List> getChangeSets() { ChangeLogSet cs = getChangeSet(); - return cs.isEmptySet() ? Collections.emptyList() : Collections.singletonList(cs); + return cs.isEmptySet() ? Collections.emptyList() : List.of(cs); } /** @@ -995,7 +995,7 @@ public EnvironmentList getEnvironments() { return new EnvironmentList(buildEnvironments); } - return new EnvironmentList(buildEnvironments == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(buildEnvironments))); + return new EnvironmentList(buildEnvironments == null ? Collections.emptyList() : List.copyOf(buildEnvironments)); } public Calendar due() { diff --git a/core/src/main/java/hudson/model/Actionable.java b/core/src/main/java/hudson/model/Actionable.java index 6fcb173fc6ad..053fb0c8cfe0 100644 --- a/core/src/main/java/hudson/model/Actionable.java +++ b/core/src/main/java/hudson/model/Actionable.java @@ -31,6 +31,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; @@ -227,7 +228,7 @@ public boolean removeAction(@Nullable Action a) { return false; } // CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way: - return getActions().removeAll(Collections.singleton(a)); + return getActions().removeAll(Set.of(a)); } /** diff --git a/core/src/main/java/hudson/model/Descriptor.java b/core/src/main/java/hudson/model/Descriptor.java index e276c54e6397..f4f16466b501 100644 --- a/core/src/main/java/hudson/model/Descriptor.java +++ b/core/src/main/java/hudson/model/Descriptor.java @@ -59,13 +59,13 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; @@ -863,7 +863,7 @@ Permission getRequiredGlobalConfigPagePermission() { } private String getViewPage(Class clazz, String pageName, String defaultValue) { - return getViewPage(clazz, Collections.singleton(pageName), defaultValue); + return getViewPage(clazz, Set.of(pageName), defaultValue); } private String getViewPage(Class clazz, Collection pageNames, String defaultValue) { @@ -978,7 +978,7 @@ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, rsp.setContentType("text/html;charset=UTF-8"); try (InputStream in = url.openStream()) { String literal = IOUtils.toString(in, StandardCharsets.UTF_8); - rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL", req.getContextPath()))); + rsp.getWriter().println(Util.replaceMacro(literal, Map.of("rootURL", req.getContextPath()))); } return; } diff --git a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java index 1df1e1ab69a8..ba62d01eb6c9 100644 --- a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java +++ b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java @@ -39,7 +39,6 @@ import java.util.Arrays; import java.util.Calendar; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.LinkedHashMap; @@ -507,10 +506,7 @@ private List buildParentPath(String pathList, int restSize) { private static String createBackRef(int times) { if (times == 0) return "./"; - StringBuilder buf = new StringBuilder(3 * times); - for (int i = 0; i < times; i++) - buf.append("../"); - return buf.toString(); + return "../".repeat(times); } private static void zip(StaplerResponse rsp, VirtualFile root, VirtualFile dir, String glob) throws IOException, InterruptedException { @@ -764,7 +760,7 @@ private static List> buildChildPaths(VirtualFile cur, Locale locale) for (VirtualFile f : files) { Path p = new Path(Util.rawEncode(f.getName()), f.getName(), f.isDirectory(), f.length(), f.canRead(), f.lastModified()); if (!f.isDirectory()) { - r.add(Collections.singletonList(p)); + r.add(List.of(p)); } else { // find all empty intermediate directory List l = new ArrayList<>(); diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index 000ef9f48d2f..b9a5610c4e35 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -388,7 +388,7 @@ public FormValidation updateNow() throws IOException { } String jsonString; try { - jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); + jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e); diff --git a/core/src/main/java/hudson/model/JDK.java b/core/src/main/java/hudson/model/JDK.java index ae642aba3305..50de1401f029 100644 --- a/core/src/main/java/hudson/model/JDK.java +++ b/core/src/main/java/hudson/model/JDK.java @@ -197,7 +197,7 @@ public List getDefaultInstallers() { Class jdkInstallerClass = Jenkins.get().getPluginManager() .uberClassLoader.loadClass("hudson.tools.JDKInstaller").asSubclass(ToolInstaller.class); Constructor constructor = jdkInstallerClass.getConstructor(String.class, boolean.class); - return Collections.singletonList(constructor.newInstance(null, false)); + return List.of(constructor.newInstance(null, false)); } catch (ClassNotFoundException e) { return Collections.emptyList(); } catch (Exception e) { diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java index 9b492f4f6cfa..449475ef2a7d 100644 --- a/core/src/main/java/hudson/model/Job.java +++ b/core/src/main/java/hudson/model/Job.java @@ -81,6 +81,7 @@ import java.util.GregorianCalendar; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.SortedMap; import java.util.logging.Level; import java.util.logging.Logger; @@ -505,7 +506,7 @@ public void suggest(String token, List result) { @Override public Collection getAllJobs() { - return Collections.singleton(this); + return Set.of(this); } /** diff --git a/core/src/main/java/hudson/model/JobProperty.java b/core/src/main/java/hudson/model/JobProperty.java index fe02891987e9..14ff87591fe9 100644 --- a/core/src/main/java/hudson/model/JobProperty.java +++ b/core/src/main/java/hudson/model/JobProperty.java @@ -36,6 +36,7 @@ import java.io.IOException; import java.util.Collection; import java.util.Collections; +import java.util.List; import jenkins.model.Jenkins; import jenkins.model.OptionalJobProperty; import net.sf.json.JSONObject; @@ -134,7 +135,7 @@ public Collection getJobActions(J job) { // delegate to getJobAction (singular) for backward compatible behavior Action a = getJobAction(job); if (a == null) return Collections.emptyList(); - return Collections.singletonList(a); + return List.of(a); } // diff --git a/core/src/main/java/hudson/model/ListView.java b/core/src/main/java/hudson/model/ListView.java index 9f47962b92bd..3476b81cc035 100644 --- a/core/src/main/java/hudson/model/ListView.java +++ b/core/src/main/java/hudson/model/ListView.java @@ -143,7 +143,7 @@ protected Object readResolve() { includePattern = Pattern.compile(includeRegex); } catch (PatternSyntaxException x) { includeRegex = null; - OldDataMonitor.report(this, Collections.singleton(x)); + OldDataMonitor.report(this, Set.of(x)); } } synchronized (this) { diff --git a/core/src/main/java/hudson/model/ParametersDefinitionProperty.java b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java index 26b59fdf95f6..d3eb4fec929a 100644 --- a/core/src/main/java/hudson/model/ParametersDefinitionProperty.java +++ b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java @@ -39,8 +39,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import jenkins.model.Jenkins; @@ -112,7 +112,7 @@ public List getParameterDefinitionNames() { @NonNull @Override public Collection getJobActions(Job job) { - return Collections.singleton(this); + return Set.of(this); } @Deprecated diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index 982c74c22380..9105ffb0bd1d 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -1987,7 +1987,7 @@ default boolean isConcurrentBuild() { * @since 1.377 */ default Collection getSubTasks() { - return Collections.singleton(this); + return Set.of(this); } /** diff --git a/core/src/main/java/hudson/model/Slave.java b/core/src/main/java/hudson/model/Slave.java index 1833acf9501a..cf6e6b437862 100644 --- a/core/src/main/java/hudson/model/Slave.java +++ b/core/src/main/java/hudson/model/Slave.java @@ -59,10 +59,7 @@ import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.jar.JarFile; @@ -744,5 +741,5 @@ private Object readResolve() { /** * Provides a collection of file names, which are accessible via /jnlpJars link. */ - private static final Set ALLOWED_JNLPJARS_FILES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("agent.jar", "slave.jar", "remoting.jar", "jenkins-cli.jar", "hudson-cli.jar"))); + private static final Set ALLOWED_JNLPJARS_FILES = Set.of("agent.jar", "slave.jar", "remoting.jar", "jenkins-cli.jar", "hudson-cli.jar"); } diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index 014559c8ab05..6615369eb33f 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -49,6 +49,7 @@ import java.net.URI; import java.net.URL; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -215,7 +216,7 @@ public long getDataTimestamp() { @Restricted(NoExternalUse.class) public @NonNull FormValidation updateDirectlyNow(boolean signatureCheck) throws IOException { - return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))), signatureCheck); + return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))), signatureCheck); } private FormValidation updateData(String json, boolean signatureCheck) diff --git a/core/src/main/java/hudson/model/User.java b/core/src/main/java/hudson/model/User.java index bc2a86138d1a..8f9ca606dca9 100644 --- a/core/src/main/java/hudson/model/User.java +++ b/core/src/main/java/hudson/model/User.java @@ -441,7 +441,7 @@ private LegitimateButUnknownUserDetails(String username) throws IllegalArgumentE super( username, "", true, true, true, true, - Collections.singleton(SecurityRealm.AUTHENTICATED_AUTHORITY2) + Set.of(SecurityRealm.AUTHENTICATED_AUTHORITY2) ); } } diff --git a/core/src/main/java/hudson/model/labels/LabelAtom.java b/core/src/main/java/hudson/model/labels/LabelAtom.java index 52779eb6fce1..84ee083c488d 100644 --- a/core/src/main/java/hudson/model/labels/LabelAtom.java +++ b/core/src/main/java/hudson/model/labels/LabelAtom.java @@ -170,7 +170,7 @@ public V accept(LabelVisitor visitor, P param) { @Override public Set listAtoms() { - return Collections.singleton(this); + return Set.of(this); } @Override diff --git a/core/src/main/java/hudson/os/SU.java b/core/src/main/java/hudson/os/SU.java index 185110d83781..d98520ab5ae1 100644 --- a/core/src/main/java/hudson/os/SU.java +++ b/core/src/main/java/hudson/os/SU.java @@ -93,7 +93,7 @@ protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { Process p = pb.start(); // TODO: use -p to detect prompt // TODO: detect if the password didn't work - try (PrintStream ps = new PrintStream(p.getOutputStream(), false, Charset.defaultCharset().name())) { + try (PrintStream ps = new PrintStream(p.getOutputStream(), false, Charset.defaultCharset())) { ps.println(rootPassword); ps.println(rootPassword); ps.println(rootPassword); diff --git a/core/src/main/java/hudson/os/WindowsUtil.java b/core/src/main/java/hudson/os/WindowsUtil.java index 7ec4637e59e1..291d87a085b3 100644 --- a/core/src/main/java/hudson/os/WindowsUtil.java +++ b/core/src/main/java/hudson/os/WindowsUtil.java @@ -70,9 +70,7 @@ public class WindowsUtil { } // else backslashes have no special meaning and don't need to be escaped here - for (int j = 0; j < nrBackslashes; j++) { - sb.append('\\'); - } + sb.append("\\".repeat(Math.max(0, nrBackslashes))); if (i < end) { sb.append(argument.charAt(i)); diff --git a/core/src/main/java/hudson/scm/EditType.java b/core/src/main/java/hudson/scm/EditType.java index 7672b09db2e4..62967b114205 100644 --- a/core/src/main/java/hudson/scm/EditType.java +++ b/core/src/main/java/hudson/scm/EditType.java @@ -24,8 +24,6 @@ package hudson.scm; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import org.kohsuke.stapler.export.CustomExportedBean; @@ -60,5 +58,5 @@ public String toExportedObject() { public static final EditType EDIT = new EditType("edit", "The file was modified"); public static final EditType DELETE = new EditType("delete", "The file was removed"); - public static final List ALL = Collections.unmodifiableList(Arrays.asList(ADD, EDIT, DELETE)); + public static final List ALL = List.of(ADD, EDIT, DELETE); } diff --git a/core/src/main/java/hudson/security/BasicAuthenticationFilter.java b/core/src/main/java/hudson/security/BasicAuthenticationFilter.java index dd29dc3004fe..b2a06024278b 100644 --- a/core/src/main/java/hudson/security/BasicAuthenticationFilter.java +++ b/core/src/main/java/hudson/security/BasicAuthenticationFilter.java @@ -29,6 +29,7 @@ import hudson.util.Scrambler; import java.io.IOException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -168,7 +169,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha // ... but first let the container authenticate this request RequestDispatcher d = servletContext.getRequestDispatcher("/j_security_check?j_username=" + - URLEncoder.encode(username, "UTF-8") + "&j_password=" + URLEncoder.encode(password, "UTF-8")); + URLEncoder.encode(username, StandardCharsets.UTF_8) + "&j_password=" + URLEncoder.encode(password, StandardCharsets.UTF_8)); d.include(req, rsp); } diff --git a/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java b/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java index c81c642650ff..d87b38cbc0ea 100644 --- a/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java +++ b/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java @@ -82,7 +82,7 @@ public void commence(HttpServletRequest req, HttpServletResponse rsp, Authentica String uriFrom = req.getRequestURI(); if (req.getQueryString() != null && !req.getQueryString().isEmpty()) uriFrom += "?" + req.getQueryString(); String loginForm = req.getContextPath() + loginFormUrl; - loginForm = MessageFormat.format(loginForm, URLEncoder.encode(uriFrom, "UTF-8")); + loginForm = MessageFormat.format(loginForm, URLEncoder.encode(uriFrom, StandardCharsets.UTF_8)); req.setAttribute("loginForm", loginForm); rsp.setStatus(SC_FORBIDDEN); diff --git a/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java b/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java index cbbe491e0e70..72d578cce67a 100644 --- a/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java +++ b/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java @@ -56,6 +56,7 @@ import java.util.HashMap; import java.util.List; import java.util.Random; +import java.util.Set; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -586,7 +587,7 @@ public User getUser(String id) { } // TODO - private static final Collection TEST_AUTHORITY = Collections.singleton(AUTHENTICATED_AUTHORITY2); + private static final Collection TEST_AUTHORITY = Set.of(AUTHENTICATED_AUTHORITY2); public static final class SignupInfo { public String username, password1, password2, fullname, email, captcha; diff --git a/core/src/main/java/hudson/security/LegacyAuthorizationStrategy.java b/core/src/main/java/hudson/security/LegacyAuthorizationStrategy.java index f9285262d9ac..39144b65b291 100644 --- a/core/src/main/java/hudson/security/LegacyAuthorizationStrategy.java +++ b/core/src/main/java/hudson/security/LegacyAuthorizationStrategy.java @@ -28,7 +28,7 @@ import hudson.Extension; import hudson.model.Descriptor; import java.util.Collection; -import java.util.Collections; +import java.util.Set; import jenkins.model.Jenkins; import org.acegisecurity.acls.sid.GrantedAuthoritySid; import org.jenkinsci.Symbol; @@ -55,7 +55,7 @@ public ACL getRootACL() { @Override public Collection getGroups() { - return Collections.singleton("admin"); + return Set.of("admin"); } @Extension @Symbol("legacy") diff --git a/core/src/main/java/hudson/security/Permission.java b/core/src/main/java/hudson/security/Permission.java index 088266ae360f..05d68d10ba62 100644 --- a/core/src/main/java/hudson/security/Permission.java +++ b/core/src/main/java/hudson/security/Permission.java @@ -27,10 +27,8 @@ import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.Hudson; -import java.util.Arrays; import java.util.Collections; import java.util.Comparator; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; @@ -150,7 +148,7 @@ public Permission(@NonNull PermissionGroup group, @NonNull String name, this.description = description; this.impliedBy = impliedBy; this.enabled = enable; - this.scopes = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(scopes))); + this.scopes = Set.of(scopes); this.id = owner.getName() + '.' + name; group.add(this); diff --git a/core/src/main/java/hudson/security/PermissionScope.java b/core/src/main/java/hudson/security/PermissionScope.java index 126d158cad07..60eae23ea99b 100644 --- a/core/src/main/java/hudson/security/PermissionScope.java +++ b/core/src/main/java/hudson/security/PermissionScope.java @@ -32,9 +32,6 @@ import hudson.model.ModelObject; import hudson.model.Node; import hudson.model.Run; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import java.util.Set; import jenkins.model.Jenkins; @@ -71,7 +68,7 @@ public final class PermissionScope { public PermissionScope(Class modelClass, PermissionScope... containers) { this.modelClass = modelClass; - this.containers = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(containers))); + this.containers = Set.of(containers); } /** diff --git a/core/src/main/java/hudson/security/SecurityRealm.java b/core/src/main/java/hudson/security/SecurityRealm.java index f2ad1fa7b63d..ca62a4d3fe0e 100644 --- a/core/src/main/java/hudson/security/SecurityRealm.java +++ b/core/src/main/java/hudson/security/SecurityRealm.java @@ -37,11 +37,10 @@ import hudson.util.DescriptorList; import hudson.util.PluginServletFilter; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; @@ -617,7 +616,7 @@ public Filter createFilter(FilterConfig filterConfig) { protected final List commonFilters() { // like Jenkins.ANONYMOUS: - AnonymousAuthenticationFilter apf = new AnonymousAuthenticationFilter("anonymous", "anonymous", Collections.singletonList(new SimpleGrantedAuthority("anonymous"))); + AnonymousAuthenticationFilter apf = new AnonymousAuthenticationFilter("anonymous", "anonymous", List.of(new SimpleGrantedAuthority("anonymous"))); ExceptionTranslationFilter etf = new ExceptionTranslationFilter(new HudsonAuthenticationEntryPoint("/" + getLoginUrl() + "?from={0}")); etf.setAccessDeniedHandler(new AccessDeniedHandlerImpl()); UnwrapSecurityExceptionFilter usef = new UnwrapSecurityExceptionFilter(); @@ -640,7 +639,7 @@ protected final List commonFilters() { */ @Restricted(DoNotUse.class) public static String getFrom() { - String from = null, returnValue = null; + String from = null; final StaplerRequest request = Stapler.getCurrentRequest(); // Try to obtain a return point from the query parameter @@ -664,9 +663,7 @@ public static String getFrom() { from = StringUtils.defaultIfBlank(from, "/").trim(); // Encode the return value - try { - returnValue = URLEncoder.encode(from, "UTF-8"); - } catch (UnsupportedEncodingException e) { } + String returnValue = URLEncoder.encode(from, StandardCharsets.UTF_8); // Return encoded value or at least "/" in the case exception occurred during encode() // or if the encoded content is blank value diff --git a/core/src/main/java/hudson/security/WhoAmI.java b/core/src/main/java/hudson/security/WhoAmI.java index 784cef76f1b8..9bde9c17e5af 100644 --- a/core/src/main/java/hudson/security/WhoAmI.java +++ b/core/src/main/java/hudson/security/WhoAmI.java @@ -6,9 +6,6 @@ import hudson.model.Api; import hudson.model.UnprotectedRootAction; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; @@ -31,11 +28,11 @@ @Extension @Symbol("whoAmI") @ExportedBean public class WhoAmI implements UnprotectedRootAction { - private static final Set dangerousHeaders = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + private static final Set dangerousHeaders = Set.of( "cookie", // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#Authentication "authorization", "www-authenticate", "proxy-authenticate", "proxy-authorization" - ))); + ); public Api getApi() { return new Api(this); diff --git a/core/src/main/java/hudson/slaves/NodeProvisioner.java b/core/src/main/java/hudson/slaves/NodeProvisioner.java index 87a0d7d45c1a..d1a6a10612da 100644 --- a/core/src/main/java/hudson/slaves/NodeProvisioner.java +++ b/core/src/main/java/hudson/slaves/NodeProvisioner.java @@ -45,7 +45,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutionException; @@ -319,7 +318,7 @@ private void update() { if (provisioningState != null) { List strategies = Jenkins.get().getExtensionList(Strategy.class); for (Strategy strategy : strategies.isEmpty() - ? Collections.singletonList(new StandardStrategyImpl()) + ? List.of(new StandardStrategyImpl()) : strategies) { LOGGER.log(Level.FINER, "Consulting {0} provisioning strategy with state {1}", new Object[]{strategy, provisioningState}); diff --git a/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java b/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java index 5feacaf28db5..e71e244a11f0 100644 --- a/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java +++ b/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java @@ -40,6 +40,7 @@ import java.io.IOException; import java.util.Collection; import java.util.Collections; +import java.util.List; import jenkins.tasks.SimpleBuildStep; /** @@ -103,7 +104,7 @@ public Collection getProjectActions(AbstractProject proj // delegate to getJobAction (singular) for backward compatible behavior Action a = getProjectAction(project); if (a == null) return Collections.emptyList(); - return Collections.singletonList(a); + return List.of(a); } diff --git a/core/src/main/java/hudson/tasks/BuildWrapper.java b/core/src/main/java/hudson/tasks/BuildWrapper.java index e6fc50da73f3..c4b7aa86a2d0 100644 --- a/core/src/main/java/hudson/tasks/BuildWrapper.java +++ b/core/src/main/java/hudson/tasks/BuildWrapper.java @@ -44,6 +44,7 @@ import java.io.OutputStream; import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Set; import jenkins.model.Jenkins; @@ -291,7 +292,7 @@ public Collection getProjectActions(AbstractProject job) { // delegate to getJobAction (singular) for backward compatible behavior Action a = getProjectAction(job); if (a == null) return Collections.emptyList(); - return Collections.singletonList(a); + return List.of(a); } /** diff --git a/core/src/main/java/hudson/tasks/Maven.java b/core/src/main/java/hudson/tasks/Maven.java index beee7b8624d5..404c21410d6f 100644 --- a/core/src/main/java/hudson/tasks/Maven.java +++ b/core/src/main/java/hudson/tasks/Maven.java @@ -693,7 +693,7 @@ public String getDisplayName() { @Override public List getDefaultInstallers() { - return Collections.singletonList(new MavenInstaller(null)); + return List.of(new MavenInstaller(null)); } // overriding them for backward compatibility. diff --git a/core/src/main/java/hudson/triggers/SCMTrigger.java b/core/src/main/java/hudson/triggers/SCMTrigger.java index 0c054c70bd73..c46902292173 100644 --- a/core/src/main/java/hudson/triggers/SCMTrigger.java +++ b/core/src/main/java/hudson/triggers/SCMTrigger.java @@ -205,7 +205,7 @@ public Collection getProjectActions() { return Collections.emptyList(); } - return Collections.singleton(new SCMAction()); + return Set.of(new SCMAction()); } /** diff --git a/core/src/main/java/hudson/triggers/Trigger.java b/core/src/main/java/hudson/triggers/Trigger.java index 896143cba390..bbe02fcb8d00 100644 --- a/core/src/main/java/hudson/triggers/Trigger.java +++ b/core/src/main/java/hudson/triggers/Trigger.java @@ -150,7 +150,7 @@ public Collection getProjectActions() { // delegate to getJobAction (singular) for backward compatible behavior Action a = getProjectAction(); if (a == null) return Collections.emptyList(); - return Collections.singletonList(a); + return List.of(a); } @Override diff --git a/core/src/main/java/hudson/util/ChunkedInputStream.java b/core/src/main/java/hudson/util/ChunkedInputStream.java index 865251c2f1ca..cfe61a17fcf1 100644 --- a/core/src/main/java/hudson/util/ChunkedInputStream.java +++ b/core/src/main/java/hudson/util/ChunkedInputStream.java @@ -261,7 +261,7 @@ private static int getChunkSizeFromInputStream(final InputStream in) } //parse data - String dataString = new String(baos.toByteArray(), StandardCharsets.US_ASCII); + String dataString = baos.toString(StandardCharsets.US_ASCII); int separator = dataString.indexOf(';'); dataString = separator > 0 ? dataString.substring(0, separator).trim() diff --git a/core/src/main/java/hudson/util/ColorPalette.java b/core/src/main/java/hudson/util/ColorPalette.java index d3aee355a927..10c22e997c11 100644 --- a/core/src/main/java/hudson/util/ColorPalette.java +++ b/core/src/main/java/hudson/util/ColorPalette.java @@ -26,8 +26,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.awt.Color; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import org.jfree.chart.renderer.category.LineAndShapeRenderer; @@ -48,12 +46,12 @@ public class ColorPalette { * Color list usable for generating line charts. */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "used in several plugins") - public static List LINE_GRAPH = Collections.unmodifiableList(Arrays.asList( + public static List LINE_GRAPH = List.of( new Color(0xCC0000), new Color(0x3465a4), new Color(0x73d216), new Color(0xedd400) - )); + ); /** * Applies {@link #LINE_GRAPH} colors to the given renderer. diff --git a/core/src/main/java/hudson/util/LogTaskListener.java b/core/src/main/java/hudson/util/LogTaskListener.java index 267f8f7bf27f..20c6212924e9 100644 --- a/core/src/main/java/hudson/util/LogTaskListener.java +++ b/core/src/main/java/hudson/util/LogTaskListener.java @@ -31,7 +31,6 @@ import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; -import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.logging.Level; import java.util.logging.LogRecord; @@ -86,12 +85,7 @@ public void write(int b) throws IOException { @Override public void flush() throws IOException { if (baos.size() > 0) { - LogRecord lr; - try { - lr = new LogRecord(level, baos.toString(StandardCharsets.UTF_8.name())); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + LogRecord lr = new LogRecord(level, baos.toString(StandardCharsets.UTF_8)); lr.setLoggerName(logger.getName()); lr.setSourceClassName(caller.getClassName()); lr.setSourceMethodName(caller.getMethodName()); diff --git a/core/src/main/java/hudson/util/PersistedList.java b/core/src/main/java/hudson/util/PersistedList.java index ba9bf455d35a..5a93a69641c8 100644 --- a/core/src/main/java/hudson/util/PersistedList.java +++ b/core/src/main/java/hudson/util/PersistedList.java @@ -39,10 +39,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.AbstractList; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Optional; @@ -202,7 +199,7 @@ protected void onModified() throws IOException { } // TODO until https://github.com/jenkinsci/jenkins-test-harness/pull/243 is widely adopted: - private static final Set IGNORED_CLASSES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("org.jvnet.hudson.test.TestBuilder", "org.jvnet.hudson.test.TestNotifier"))); + private static final Set IGNORED_CLASSES = Set.of("org.jvnet.hudson.test.TestBuilder", "org.jvnet.hudson.test.TestNotifier"); // (SingleFileSCM & ExtractResourceWithChangesSCM would also be nice to suppress, but they are not kept in a PersistedList.) private static boolean ignoreSerializationErrors(Object o) { diff --git a/core/src/main/java/hudson/util/ProcessTree.java b/core/src/main/java/hudson/util/ProcessTree.java index 3e087106f90d..6060ee0f5b5b 100644 --- a/core/src/main/java/hudson/util/ProcessTree.java +++ b/core/src/main/java/hudson/util/ProcessTree.java @@ -56,7 +56,6 @@ import java.io.ObjectStreamException; import java.io.RandomAccessFile; import java.io.Serializable; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -1352,12 +1351,7 @@ private String readLine(int fd, long addr, String prefix) throws IOException { buf.write(ch); addr++; } - String line; - try { - line = buf.toString(StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + String line = buf.toString(StandardCharsets.UTF_8); if (LOGGER.isLoggable(FINEST)) LOGGER.finest(prefix + " was " + line); return line; @@ -1628,12 +1622,7 @@ private String readLine(int fd, long addr, String prefix) throws IOException { buf.write(ch); addr++; } - String line; - try { - line = buf.toString(StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + String line = buf.toString(StandardCharsets.UTF_8); if (LOGGER.isLoggable(FINEST)) LOGGER.finest(prefix + " was " + line); return line; @@ -1801,11 +1790,7 @@ String readString() { byte ch; while (offset < length && (ch = getByte(offset++)) != '\0') baos.write(ch); - try { - return baos.toString(StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return baos.toString(StandardCharsets.UTF_8); } void skip0() { @@ -2119,11 +2104,7 @@ private void parse(Memory m, NativeLong size, Consumer consumer) { while ((ch = m.getByte(offset++)) != '\0') { baos.write(ch); } - try { - consumer.accept(baos.toString(StandardCharsets.UTF_8.name())); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + consumer.accept(baos.toString(StandardCharsets.UTF_8)); baos.reset(); } } diff --git a/core/src/main/java/hudson/util/QueryParameterMap.java b/core/src/main/java/hudson/util/QueryParameterMap.java index a187ae8ccabc..c4cf323d8ca8 100644 --- a/core/src/main/java/hudson/util/QueryParameterMap.java +++ b/core/src/main/java/hudson/util/QueryParameterMap.java @@ -24,8 +24,8 @@ package hudson.util; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -57,16 +57,12 @@ public class QueryParameterMap { */ public QueryParameterMap(String queryString) { if (queryString == null || queryString.length() == 0) return; - try { - for (String param : queryString.split("&")) { - String[] kv = param.split("="); - String key = URLDecoder.decode(kv[0], "UTF-8"); - String value = URLDecoder.decode(kv[1], "UTF-8"); - List values = store.computeIfAbsent(key, k -> new ArrayList<>()); - values.add(value); - } - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); + for (String param : queryString.split("&")) { + String[] kv = param.split("="); + String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8); + String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + List values = store.computeIfAbsent(key, k -> new ArrayList<>()); + values.add(value); } } diff --git a/core/src/main/java/hudson/util/RemotingDiagnostics.java b/core/src/main/java/hudson/util/RemotingDiagnostics.java index 187ba1112a48..57b339cb9a00 100644 --- a/core/src/main/java/hudson/util/RemotingDiagnostics.java +++ b/core/src/main/java/hudson/util/RemotingDiagnostics.java @@ -43,7 +43,6 @@ import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.nio.file.Files; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; @@ -70,7 +69,7 @@ public final class RemotingDiagnostics { public static Map getSystemProperties(VirtualChannel channel) throws IOException, InterruptedException { if (channel == null) - return Collections.singletonMap("N/A", "N/A"); + return Map.of("N/A", "N/A"); return channel.call(new GetSystemProperties()); } @@ -85,13 +84,13 @@ public Map call() { public static Map getThreadDump(VirtualChannel channel) throws IOException, InterruptedException { if (channel == null) - return Collections.singletonMap("N/A", "N/A"); + return Map.of("N/A", "N/A"); return channel.call(new GetThreadDump()); } public static Future> getThreadDumpAsync(VirtualChannel channel) throws IOException, InterruptedException { if (channel == null) - return new AsyncFutureImpl<>(Collections.singletonMap("N/A", "offline")); + return new AsyncFutureImpl<>(Map.of("N/A", "offline")); return channel.callAsync(new GetThreadDump()); } diff --git a/core/src/main/java/hudson/util/StreamTaskListener.java b/core/src/main/java/hudson/util/StreamTaskListener.java index f19db94b45cd..4abe31d3ec51 100644 --- a/core/src/main/java/hudson/util/StreamTaskListener.java +++ b/core/src/main/java/hudson/util/StreamTaskListener.java @@ -36,7 +36,6 @@ import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintStream; -import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Files; @@ -86,16 +85,12 @@ public StreamTaskListener(@NonNull OutputStream out) { } public StreamTaskListener(@NonNull OutputStream out, @CheckForNull Charset charset) { - try { - if (charset == null) - this.out = out instanceof PrintStream ? (PrintStream) out : new PrintStream(out, false, Charset.defaultCharset().name()); - else - this.out = new PrintStream(out, false, charset.name()); - this.charset = charset; - } catch (UnsupportedEncodingException e) { - // it's not very pretty to do this, but otherwise we'd have to touch too many call sites. - throw new Error(e); + if (charset == null) { + this.out = out instanceof PrintStream ? (PrintStream) out : new PrintStream(out, false, Charset.defaultCharset()); + } else { + this.out = new PrintStream(out, false, charset); } + this.charset = charset; } /** diff --git a/core/src/main/java/jenkins/PluginSubtypeMarker.java b/core/src/main/java/jenkins/PluginSubtypeMarker.java index de529f929afd..0bcb5684b696 100644 --- a/core/src/main/java/jenkins/PluginSubtypeMarker.java +++ b/core/src/main/java/jenkins/PluginSubtypeMarker.java @@ -41,7 +41,7 @@ import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.ElementScanner6; +import javax.lang.model.util.ElementScanner9; import javax.tools.Diagnostic; import javax.tools.FileObject; import javax.tools.StandardLocation; @@ -59,7 +59,7 @@ public class PluginSubtypeMarker extends AbstractProcessor { @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { try { - ElementScanner6 scanner = new ElementScanner6() { + ElementScanner9 scanner = new ElementScanner9() { @Override public Void visitType(TypeElement e, Void aVoid) { if (!e.getModifiers().contains(Modifier.ABSTRACT)) { diff --git a/core/src/main/java/jenkins/model/GlobalBuildDiscarderConfiguration.java b/core/src/main/java/jenkins/model/GlobalBuildDiscarderConfiguration.java index ed0821a88556..023eb52a4ff6 100644 --- a/core/src/main/java/jenkins/model/GlobalBuildDiscarderConfiguration.java +++ b/core/src/main/java/jenkins/model/GlobalBuildDiscarderConfiguration.java @@ -28,7 +28,7 @@ import hudson.ExtensionList; import hudson.util.DescribableList; import java.io.IOException; -import java.util.Collections; +import java.util.List; import net.sf.json.JSONObject; import org.jenkinsci.Symbol; import org.kohsuke.accmod.Restricted; @@ -53,7 +53,7 @@ public GlobalBuildDiscarderConfiguration() { } private final DescribableList configuredBuildDiscarders = - new DescribableList<>(this, Collections.singletonList(new JobGlobalBuildDiscarderStrategy())); + new DescribableList<>(this, List.of(new JobGlobalBuildDiscarderStrategy())); private Object readResolve() { configuredBuildDiscarders.setOwner(this); diff --git a/core/src/main/java/jenkins/model/Jenkins.java b/core/src/main/java/jenkins/model/Jenkins.java index 511ee7a610eb..25239fcd16e6 100644 --- a/core/src/main/java/jenkins/model/Jenkins.java +++ b/core/src/main/java/jenkins/model/Jenkins.java @@ -4162,7 +4162,7 @@ public Map> getAllThreadDumps() throws IOException, try { r.put(e.getKey(), e.getValue().get(endTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS)); } catch (Exception x) { - r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump", Functions.printThrowable(x))); + r.put(e.getKey(), Map.of("Failed to retrieve thread dump", Functions.printThrowable(x))); } } return Collections.unmodifiableSortedMap(new TreeMap<>(r)); @@ -5678,7 +5678,7 @@ public boolean shouldShowStackTrace() { new AnonymousAuthenticationToken( "anonymous", "anonymous", - Collections.singleton(new SimpleGrantedAuthority("anonymous"))); + Set.of(new SimpleGrantedAuthority("anonymous"))); /** * @deprecated use {@link #ANONYMOUS2} diff --git a/core/src/main/java/jenkins/model/NewViewLink.java b/core/src/main/java/jenkins/model/NewViewLink.java index 17946e547236..65ce84928c34 100644 --- a/core/src/main/java/jenkins/model/NewViewLink.java +++ b/core/src/main/java/jenkins/model/NewViewLink.java @@ -26,7 +26,7 @@ public List createFor(final View v) { // do not show the action if the viewgroup is not modifiable ViewGroup vg = v.getOwner(); if (vg instanceof ModifiableViewGroup) { - return Collections.singletonList(new NewViewLinkAction((ModifiableViewGroup) vg)); + return List.of(new NewViewLinkAction((ModifiableViewGroup) vg)); } return Collections.emptyList(); } diff --git a/core/src/main/java/jenkins/model/ParameterizedJobMixIn.java b/core/src/main/java/jenkins/model/ParameterizedJobMixIn.java index 66d40c078dd1..ae064d0183d1 100644 --- a/core/src/main/java/jenkins/model/ParameterizedJobMixIn.java +++ b/core/src/main/java/jenkins/model/ParameterizedJobMixIn.java @@ -114,7 +114,7 @@ public final boolean scheduleBuild(int quietPeriod) { /** @see BuildableItem#scheduleBuild(int, Cause) */ public final boolean scheduleBuild(int quietPeriod, Cause c) { - return scheduleBuild2(quietPeriod, c != null ? Collections.singletonList(new CauseAction(c)) : Collections.emptyList()) != null; + return scheduleBuild2(quietPeriod, c != null ? List.of(new CauseAction(c)) : Collections.emptyList()) != null; } /** diff --git a/core/src/main/java/jenkins/model/RenameAction.java b/core/src/main/java/jenkins/model/RenameAction.java index 45ddbd529040..37a75c75862d 100644 --- a/core/src/main/java/jenkins/model/RenameAction.java +++ b/core/src/main/java/jenkins/model/RenameAction.java @@ -29,6 +29,7 @@ import hudson.model.Action; import java.util.Collection; import java.util.Collections; +import java.util.Set; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; @@ -61,7 +62,7 @@ public Class type() { @Override public Collection createFor(AbstractItem target) { if (target.isNameEditable()) { - return Collections.singleton(new RenameAction()); + return Set.of(new RenameAction()); } else { return Collections.emptyList(); } diff --git a/core/src/main/java/jenkins/plugins/DetachedPluginsUtil.java b/core/src/main/java/jenkins/plugins/DetachedPluginsUtil.java index 779ab79ace89..847180257c13 100644 --- a/core/src/main/java/jenkins/plugins/DetachedPluginsUtil.java +++ b/core/src/main/java/jenkins/plugins/DetachedPluginsUtil.java @@ -9,7 +9,6 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Level; @@ -49,18 +48,18 @@ public class DetachedPluginsUtil { static { try (InputStream is = ClassicPluginStrategy.class.getResourceAsStream("/jenkins/split-plugins.txt")) { - DETACHED_LIST = Collections.unmodifiableList(configLines(is).map(line -> { + DETACHED_LIST = configLines(is).map(line -> { String[] pieces = line.split(" "); return new DetachedPluginsUtil.DetachedPlugin(pieces[0], pieces[1] + ".*", pieces[2]); - }).collect(Collectors.toList())); + }).collect(Collectors.toUnmodifiableList()); } catch (IOException x) { throw new ExceptionInInitializerError(x); } try (InputStream is = ClassicPluginStrategy.class.getResourceAsStream("/jenkins/split-plugin-cycles.txt")) { - BREAK_CYCLES = Collections.unmodifiableSet(configLines(is).collect(Collectors.toSet())); + BREAK_CYCLES = configLines(is).collect(Collectors.toUnmodifiableSet()); } catch (IOException x) { throw new ExceptionInInitializerError(x); } @@ -103,7 +102,7 @@ public static List getImpliedDependencies(String plugi */ public static @NonNull List getDetachedPlugins() { - return Collections.unmodifiableList(new ArrayList<>(DETACHED_LIST)); + return List.copyOf(DETACHED_LIST); } /** diff --git a/core/src/main/java/jenkins/scm/RunWithSCM.java b/core/src/main/java/jenkins/scm/RunWithSCM.java index f1fd092bf5ce..9a4d19b8c721 100644 --- a/core/src/main/java/jenkins/scm/RunWithSCM.java +++ b/core/src/main/java/jenkins/scm/RunWithSCM.java @@ -35,7 +35,6 @@ import hudson.scm.SCM; import hudson.util.AdaptedIterator; import java.util.AbstractSet; -import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -97,7 +96,7 @@ public interface RunWithSCM, } return new AbstractSet() { - private Set culpritIds = Collections.unmodifiableSet(new HashSet<>(getCulpritIds())); + private Set culpritIds = Set.copyOf(getCulpritIds()); @Override public Iterator iterator() { diff --git a/core/src/main/java/jenkins/security/ApiTokenFilter.java b/core/src/main/java/jenkins/security/ApiTokenFilter.java index 6de444b0ae34..986408d62604 100644 --- a/core/src/main/java/jenkins/security/ApiTokenFilter.java +++ b/core/src/main/java/jenkins/security/ApiTokenFilter.java @@ -1,6 +1,5 @@ package jenkins.security; -import java.util.Collections; import java.util.List; import javax.servlet.Filter; @@ -20,6 +19,6 @@ public class ApiTokenFilter extends BasicHeaderProcessor { @Override protected List all() { - return Collections.singletonList(new BasicHeaderApiTokenAuthenticator()); + return List.of(new BasicHeaderApiTokenAuthenticator()); } } diff --git a/core/src/main/java/jenkins/security/ClassFilterImpl.java b/core/src/main/java/jenkins/security/ClassFilterImpl.java index e918ccf96b27..70c37c4c944d 100644 --- a/core/src/main/java/jenkins/security/ClassFilterImpl.java +++ b/core/src/main/java/jenkins/security/ClassFilterImpl.java @@ -117,7 +117,7 @@ private static void mockOff() { static { try (InputStream is = ClassFilterImpl.class.getResourceAsStream("whitelisted-classes.txt")) { - WHITELISTED_CLASSES = Collections.unmodifiableSet(IOUtils.readLines(is, StandardCharsets.UTF_8).stream().filter(line -> !line.matches("#.*|\\s*")).collect(Collectors.toSet())); + WHITELISTED_CLASSES = IOUtils.readLines(is, StandardCharsets.UTF_8).stream().filter(line -> !line.matches("#.*|\\s*")).collect(Collectors.toUnmodifiableSet()); } catch (IOException x) { throw new ExceptionInInitializerError(x); } diff --git a/core/src/main/java/jenkins/security/LastGrantedAuthoritiesProperty.java b/core/src/main/java/jenkins/security/LastGrantedAuthoritiesProperty.java index 0ae1f683d8d6..52f74d452ffa 100644 --- a/core/src/main/java/jenkins/security/LastGrantedAuthoritiesProperty.java +++ b/core/src/main/java/jenkins/security/LastGrantedAuthoritiesProperty.java @@ -11,8 +11,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.Jenkins; @@ -55,7 +55,7 @@ public Collection getAuthorities2() { String[] roles = this.roles; // capture to a variable for immutability if (roles == null) { - return Collections.singleton(SecurityRealm.AUTHENTICATED_AUTHORITY2); + return Set.of(SecurityRealm.AUTHENTICATED_AUTHORITY2); } String authenticatedRole = SecurityRealm.AUTHENTICATED_AUTHORITY2.getAuthority(); diff --git a/core/src/main/java/jenkins/security/stapler/WebMethodConstants.java b/core/src/main/java/jenkins/security/stapler/WebMethodConstants.java index ce33e886a83f..90e14912005d 100644 --- a/core/src/main/java/jenkins/security/stapler/WebMethodConstants.java +++ b/core/src/main/java/jenkins/security/stapler/WebMethodConstants.java @@ -25,7 +25,6 @@ package jenkins.security.stapler; import java.lang.annotation.Annotation; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; @@ -49,12 +48,12 @@ final class WebMethodConstants { /** * If a method has at least one of those parameters, it is considered as an implicit web method */ - private static final List> WEB_METHOD_PARAMETERS = Collections.unmodifiableList(Arrays.asList( + private static final List> WEB_METHOD_PARAMETERS = List.of( StaplerRequest.class, HttpServletRequest.class, StaplerResponse.class, HttpServletResponse.class - )); + ); static final Set WEB_METHOD_PARAMETERS_NAMES = Collections.unmodifiableSet( WEB_METHOD_PARAMETERS.stream() @@ -66,7 +65,7 @@ final class WebMethodConstants { * If a method is annotated with one of those annotations, * the method is considered as an explicit web method */ - static final List> WEB_METHOD_ANNOTATIONS = Collections.singletonList( + static final List> WEB_METHOD_ANNOTATIONS = List.of( WebMethod.class // plus every annotation that's annotated with InterceptorAnnotation // JavaScriptMethod.class not taken here because it's a special case @@ -86,13 +85,13 @@ final class WebMethodConstants { * If at least one parameter of the method is annotated with one of those annotations, * the method is considered as an implicit web method */ - private static final List> WEB_METHOD_PARAMETER_ANNOTATIONS = Collections.unmodifiableList(Arrays.asList( + private static final List> WEB_METHOD_PARAMETER_ANNOTATIONS = List.of( QueryParameter.class, AncestorInPath.class, Header.class, JsonBody.class, SubmittedForm.class - )); + ); static final Set WEB_METHOD_PARAMETER_ANNOTATION_NAMES = Collections.unmodifiableSet( WEB_METHOD_PARAMETER_ANNOTATIONS.stream() diff --git a/core/src/main/java/jenkins/slaves/JnlpSlaveAgentProtocol4.java b/core/src/main/java/jenkins/slaves/JnlpSlaveAgentProtocol4.java index f4fb58bbcbb8..75ef3851164a 100644 --- a/core/src/main/java/jenkins/slaves/JnlpSlaveAgentProtocol4.java +++ b/core/src/main/java/jenkins/slaves/JnlpSlaveAgentProtocol4.java @@ -37,7 +37,7 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; -import java.util.Collections; +import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; @@ -194,7 +194,7 @@ public void handle(Socket socket) throws IOException, InterruptedException { LOGGER.log(Level.FINEST, "Ignored", e); } handler.handle(socket, - Collections.singletonMap(JnlpConnectionState.COOKIE_KEY, JnlpAgentReceiver.generateCookie()), + Map.of(JnlpConnectionState.COOKIE_KEY, JnlpAgentReceiver.generateCookie()), ExtensionList.lookup(JnlpAgentReceiver.class)); } diff --git a/core/src/main/java/jenkins/triggers/SCMTriggerItem.java b/core/src/main/java/jenkins/triggers/SCMTriggerItem.java index 8461e2f3afea..5e8062c20958 100644 --- a/core/src/main/java/jenkins/triggers/SCMTriggerItem.java +++ b/core/src/main/java/jenkins/triggers/SCMTriggerItem.java @@ -38,6 +38,7 @@ import hudson.triggers.SCMTrigger; import java.util.Collection; import java.util.Collections; +import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.ParameterizedJobMixIn; @@ -167,10 +168,10 @@ private static final class Bridge implements SCMTriggerItem { return (Collection) scm.getClass().getMethod("getConfiguredSCMs").invoke(scm); } catch (Exception x) { Logger.getLogger(SCMTriggerItem.class.getName()).log(Level.WARNING, null, x); - return Collections.singleton(scm); + return Set.of(scm); } } else { - return Collections.singleton(scm); + return Set.of(scm); } } diff --git a/core/src/main/java/jenkins/util/io/PathRemover.java b/core/src/main/java/jenkins/util/io/PathRemover.java index bf8ff997d4e4..7a47ba23b6b1 100644 --- a/core/src/main/java/jenkins/util/io/PathRemover.java +++ b/core/src/main/java/jenkins/util/io/PathRemover.java @@ -72,7 +72,7 @@ private PathRemover(@NonNull RetryStrategy retryStrategy, @NonNull PathChecker p public void forceRemoveFile(@NonNull Path path) throws IOException { for (int retryAttempts = 0; ; retryAttempts++) { Optional maybeError = tryRemoveFile(path); - if (!maybeError.isPresent()) return; + if (maybeError.isEmpty()) return; if (retryStrategy.shouldRetry(retryAttempts)) continue; IOException error = maybeError.get(); throw new IOException(retryStrategy.failureMessage(path, retryAttempts), error); diff --git a/core/src/main/java/jenkins/util/xml/FilteredFunctionContext.java b/core/src/main/java/jenkins/util/xml/FilteredFunctionContext.java index e860cca3b3f5..e9a38aa4c3fb 100644 --- a/core/src/main/java/jenkins/util/xml/FilteredFunctionContext.java +++ b/core/src/main/java/jenkins/util/xml/FilteredFunctionContext.java @@ -25,8 +25,6 @@ package jenkins.util.xml; -import java.util.Collections; -import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.jaxen.Function; @@ -51,9 +49,7 @@ public class FilteredFunctionContext implements FunctionContext { /** * Default set of "bad" function names. */ - private static final Set DEFAULT_ILLEGAL_FUNCTIONS = Collections.unmodifiableSet(new HashSet<>( - Collections.singletonList("document") - )); + private static final Set DEFAULT_ILLEGAL_FUNCTIONS = Set.of("document"); private final FunctionContext base; private final Set illegalFunctions; diff --git a/core/src/main/resources/jenkins/security/whitelisted-classes.txt b/core/src/main/resources/jenkins/security/whitelisted-classes.txt index fbcdc1a9de01..c2f974a7ef9f 100644 --- a/core/src/main/resources/jenkins/security/whitelisted-classes.txt +++ b/core/src/main/resources/jenkins/security/whitelisted-classes.txt @@ -58,6 +58,7 @@ java.time.Ser java.util.ArrayDeque java.util.ArrayList java.util.Arrays$ArrayList +java.util.CollSer java.util.Collections$AsLIFOQueue java.util.Collections$CheckedCollection java.util.Collections$CheckedList @@ -103,6 +104,7 @@ java.util.GregorianCalendar java.util.HashMap java.util.HashSet java.util.Hashtable +java.util.ImmutableCollections$List12 java.util.LinkedHashMap java.util.LinkedHashSet java.util.LinkedList diff --git a/core/src/test/java/hudson/EnvVarsTest.java b/core/src/test/java/hudson/EnvVarsTest.java index 5af4b7d064b4..f0c252c09177 100644 --- a/core/src/test/java/hudson/EnvVarsTest.java +++ b/core/src/test/java/hudson/EnvVarsTest.java @@ -32,9 +32,9 @@ import hudson.EnvVars.OverrideOrderCalculator; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.TreeMap; import org.junit.jupiter.api.Test; @@ -45,7 +45,7 @@ public class EnvVarsTest { @Test public void caseInsensitive() { - EnvVars ev = new EnvVars(Collections.singletonMap("Path", "A:B:C")); + EnvVars ev = new EnvVars(Map.of("Path", "A:B:C")); assertTrue(ev.containsKey("PATH")); assertEquals("A:B:C", ev.get("PATH")); } @@ -122,7 +122,7 @@ public void overrideOrderCalculatorSelfReference() { OverrideOrderCalculator calc = new OverrideOrderCalculator(env, overrides); List order = calc.getOrderedVariableNames(); - assertEquals(Collections.singletonList("PATH"), order); + assertEquals(List.of("PATH"), order); } @Test diff --git a/core/src/test/java/hudson/FilePathTest.java b/core/src/test/java/hudson/FilePathTest.java index 33a6e8484b19..f7478712a544 100644 --- a/core/src/test/java/hudson/FilePathTest.java +++ b/core/src/test/java/hudson/FilePathTest.java @@ -640,7 +640,7 @@ private static void assertValidateAntFileMask(String expected, FilePath d, Strin String message = "going ahead"; assertFalse(d.installIfNecessaryFrom(url, new StreamTaskListener(baos, Charset.defaultCharset()), message)); verify(con).setIfModifiedSince(123000); - String log = baos.toString(Charset.defaultCharset().name()); + String log = baos.toString(Charset.defaultCharset()); assertFalse(log, log.contains(message)); assertTrue(log, log.contains("504 Gateway Timeout")); } diff --git a/core/src/test/java/hudson/FunctionsTest.java b/core/src/test/java/hudson/FunctionsTest.java index f9b42f97efca..17154218539a 100644 --- a/core/src/test/java/hudson/FunctionsTest.java +++ b/core/src/test/java/hudson/FunctionsTest.java @@ -146,7 +146,7 @@ public void testGetRelativeLinkTo_JobContainedInView() { when(j.getItemGroup()).thenReturn(j); createMockAncestors(req, createAncestor(view, "."), createAncestor(j, "../..")); TopLevelItem i = createMockItem(parent, "job/i/"); - when(view.getItems()).thenReturn(Collections.singletonList(i)); + when(view.getItems()).thenReturn(List.of(i)); String result = Functions.getRelativeLinkTo(i); assertEquals("job/i/", result); } @@ -212,7 +212,7 @@ public void testGetRelativeLinkTo_JobContainedInViewWithinItemGroup() { when(parent.getItemGroup()).thenReturn(parent); createMockAncestors(req, createAncestor(j, "../../.."), createAncestor(parent, "../.."), createAncestor(view, ".")); TopLevelItem i = createMockItem(parent, "job/i/", "parent/job/i/"); - when(view.getItems()).thenReturn(Collections.singletonList(i)); + when(view.getItems()).thenReturn(List.of(i)); String result = Functions.getRelativeLinkTo(i); assertEquals("job/i/", result); } diff --git a/core/src/test/java/hudson/LauncherTest.java b/core/src/test/java/hudson/LauncherTest.java index b1ef4befdbde..69add4199a23 100644 --- a/core/src/test/java/hudson/LauncherTest.java +++ b/core/src/test/java/hudson/LauncherTest.java @@ -95,7 +95,7 @@ public Object call() throws RuntimeException { EnvVars env = new EnvVars("key1", "val1"); Launcher decorated = base.decorateByEnv(env); int res = decorated.launch().envs("key2=val2").cmds(Functions.isWindows() ? new String[] {"cmd", "/q", "/c", "echo %key1% %key2%"} : new String[] {"sh", "-c", "echo $key1 $key2"}).stdout(l).join(); - String log = baos.toString(Charset.defaultCharset().name()); + String log = baos.toString(Charset.defaultCharset()); assertEquals(log, 0, res); assertTrue(log, log.contains("val1 val2")); } diff --git a/core/src/test/java/hudson/UtilTest.java b/core/src/test/java/hudson/UtilTest.java index 6b7a25540060..0ee6eb2a5649 100644 --- a/core/src/test/java/hudson/UtilTest.java +++ b/core/src/test/java/hudson/UtilTest.java @@ -246,7 +246,7 @@ public void testSymlink() throws Exception { buf.append((char) ('0' + (i % 10))); Util.createSymlink(d, buf.toString(), "x", l); - String log = baos.toString(Charset.defaultCharset().name()); + String log = baos.toString(Charset.defaultCharset()); if (log.length() > 0) System.err.println("log output: " + log); diff --git a/core/src/test/java/hudson/cli/ListJobsCommandTest.java b/core/src/test/java/hudson/cli/ListJobsCommandTest.java index dc8478d593ea..dd64be702a73 100644 --- a/core/src/test/java/hudson/cli/ListJobsCommandTest.java +++ b/core/src/test/java/hudson/cli/ListJobsCommandTest.java @@ -16,11 +16,9 @@ import java.io.IOException; import java.io.PrintStream; import java.io.UncheckedIOException; -import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -114,7 +112,7 @@ public void getJobsRecursivelyFromViewGroup() throws Exception { when(rootView.getViews()).thenReturn(Arrays.asList(leftView, rightView)); when(rootView.getItems()).thenReturn(Arrays.asList(rootJob, sharedJob)); when(leftView.getItems()).thenReturn(Arrays.asList(leftJob, sharedJob)); - when(rightView.getItems()).thenReturn(Collections.singletonList(rightJob)); + when(rightView.getItems()).thenReturn(List.of(rightJob)); Jenkins jenkins = mock(Jenkins.class); try (MockedStatic mocked = mockStatic(Jenkins.class)) { @@ -167,11 +165,7 @@ protected boolean matchesSafely(ByteArrayOutputStream item) { } catch (InterruptedException e) { throw new RuntimeException(e); } - try { - return item.toString(charset.name()).isEmpty(); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return item.toString(charset).isEmpty(); } @Override @@ -189,7 +183,6 @@ private TypeSafeMatcher listsJobs(final String... expecte @Override protected boolean matchesSafely(ByteArrayOutputStream item) { - Set jobs; Charset charset; try { charset = command.getClientCharset(); @@ -198,11 +191,7 @@ protected boolean matchesSafely(ByteArrayOutputStream item) { } catch (InterruptedException e) { throw new RuntimeException(e); } - try { - jobs = new HashSet<>(Arrays.asList(item.toString(charset.name()).split(System.getProperty("line.separator")))); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + Set jobs = new HashSet<>(Arrays.asList(item.toString(charset).split(System.getProperty("line.separator")))); return new HashSet<>(Arrays.asList(expected)).equals(jobs); } diff --git a/core/src/test/java/hudson/model/ActionableTest.java b/core/src/test/java/hudson/model/ActionableTest.java index 807c91acbddb..43b40fcbb158 100644 --- a/core/src/test/java/hudson/model/ActionableTest.java +++ b/core/src/test/java/hudson/model/ActionableTest.java @@ -148,11 +148,11 @@ public void removeAction() { thing.addAction(a2); assertEquals(Arrays.asList(a1, a2), thing.getActions()); assertThat(thing.removeAction(a1), is(true)); - assertEquals(Collections.singletonList(a2), thing.getActions()); + assertEquals(List.of(a2), thing.getActions()); assertThat(thing.removeAction(a1), is(false)); - assertEquals(Collections.singletonList(a2), thing.getActions()); + assertEquals(List.of(a2), thing.getActions()); assertThat(thing.removeAction(null), is(false)); - assertEquals(Collections.singletonList(a2), thing.getActions()); + assertEquals(List.of(a2), thing.getActions()); } @SuppressWarnings("deprecation") @@ -164,9 +164,9 @@ public void removeActions() { thing.addAction(a2); assertEquals(Arrays.asList(a1, a2), thing.getActions()); assertThat(thing.removeActions(CauseAction.class), is(true)); - assertEquals(Collections.singletonList(a2), thing.getActions()); + assertEquals(List.of(a2), thing.getActions()); assertThat(thing.removeActions(CauseAction.class), is(false)); - assertEquals(Collections.singletonList(a2), thing.getActions()); + assertEquals(List.of(a2), thing.getActions()); } @SuppressWarnings("deprecation") @@ -176,7 +176,7 @@ public void addAction() { ParametersAction a2 = new ParametersAction(); assertEquals(Collections.emptyList(), thing.getActions()); thing.addAction(a1); - assertEquals(Collections.singletonList(a1), thing.getActions()); + assertEquals(List.of(a1), thing.getActions()); thing.addAction(a2); assertEquals(Arrays.asList(a1, a2), thing.getActions()); } diff --git a/core/src/test/java/hudson/model/RunTest.java b/core/src/test/java/hudson/model/RunTest.java index be8adfcbb825..1c17dcffc83a 100644 --- a/core/src/test/java/hudson/model/RunTest.java +++ b/core/src/test/java/hudson/model/RunTest.java @@ -176,7 +176,7 @@ public void getLogReturnsAnEmptyListWhenCalledWith0() throws Exception { Run, ? extends Run> r = new Run(j, 0) {}; File f = r.getLogFile(); f.getParentFile().mkdirs(); - PrintWriter w = new PrintWriter(f, "utf-8"); + PrintWriter w = new PrintWriter(f, StandardCharsets.UTF_8); w.println("dummy"); w.close(); List logLines = r.getLog(0); @@ -192,7 +192,7 @@ public void getLogReturnsAnRightOrder() throws Exception { Run, ? extends Run> r = new Run(j, 0) {}; File f = r.getLogFile(); f.getParentFile().mkdirs(); - PrintWriter w = new PrintWriter(f, "utf-8"); + PrintWriter w = new PrintWriter(f, StandardCharsets.UTF_8); for (int i = 0; i < 20; i++) { w.println("dummy" + i); } @@ -217,7 +217,7 @@ public void getLogReturnsAllLines() throws Exception { Run, ? extends Run> r = new Run(j, 0) {}; File f = r.getLogFile(); f.getParentFile().mkdirs(); - PrintWriter w = new PrintWriter(f, "utf-8"); + PrintWriter w = new PrintWriter(f, StandardCharsets.UTF_8); w.print("a1\nb2\n\nc3"); w.close(); List logLines = r.getLog(10); diff --git a/core/src/test/java/hudson/model/TaskActionTest.java b/core/src/test/java/hudson/model/TaskActionTest.java index 3b0789f794c0..a7e0c1cedba5 100644 --- a/core/src/test/java/hudson/model/TaskActionTest.java +++ b/core/src/test/java/hudson/model/TaskActionTest.java @@ -6,6 +6,7 @@ import hudson.security.ACL; import hudson.security.Permission; import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; import org.junit.Test; /** @@ -68,6 +69,6 @@ public void annotatedText() throws Exception { final long length = annotatedText.writeLogTo(0, os); // Windows based systems will be 220, linux base 219 assertTrue("length should be longer or even 219", length >= 219); - assertTrue(os.toString("UTF-8").startsWith("a linkCompleted")); + assertTrue(os.toString(StandardCharsets.UTF_8).startsWith("a linkCompleted")); } } diff --git a/core/src/test/java/hudson/model/ViewTest.java b/core/src/test/java/hudson/model/ViewTest.java index e5374f133286..cd76ea6250e3 100644 --- a/core/src/test/java/hudson/model/ViewTest.java +++ b/core/src/test/java/hudson/model/ViewTest.java @@ -10,7 +10,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.List; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -94,7 +93,7 @@ public void getAllItems() { final TopLevelItem rightJob = createJob("rightJob"); Mockito.when(leftView.getItems()).thenReturn(Arrays.asList(leftJob, sharedJob)); - Mockito.when(rightView.getItems()).thenReturn(Collections.singletonList(rightJob)); + Mockito.when(rightView.getItems()).thenReturn(List.of(rightJob)); final TopLevelItem[] expected = new TopLevelItem[] {rootJob, sharedJob, leftJob, rightJob}; diff --git a/core/src/test/java/hudson/slaves/ComputerLauncherTest.java b/core/src/test/java/hudson/slaves/ComputerLauncherTest.java index 80ba6a61a74b..ae2a10005d97 100644 --- a/core/src/test/java/hudson/slaves/ComputerLauncherTest.java +++ b/core/src/test/java/hudson/slaves/ComputerLauncherTest.java @@ -143,8 +143,8 @@ public class ComputerLauncherTest { private static void assertChecked(String text, String spec) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); - ComputerLauncher.checkJavaVersion(new PrintStream(os, false, Charset.defaultCharset().name()), "bin/java", new BufferedReader(new StringReader(text))); - String logged = os.toString(Charset.defaultCharset().name()); + ComputerLauncher.checkJavaVersion(new PrintStream(os, false, Charset.defaultCharset()), "bin/java", new BufferedReader(new StringReader(text))); + String logged = os.toString(Charset.defaultCharset()); assertTrue(logged.contains(Messages.ComputerLauncher_JavaVersionResult("bin/java", spec)), logged); } } diff --git a/core/src/test/java/hudson/util/ArgumentListBuilderTest.java b/core/src/test/java/hudson/util/ArgumentListBuilderTest.java index 49183573bee0..96aad3c2d5b5 100644 --- a/core/src/test/java/hudson/util/ArgumentListBuilderTest.java +++ b/core/src/test/java/hudson/util/ArgumentListBuilderTest.java @@ -33,7 +33,6 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; @@ -199,7 +198,7 @@ public void assertMaskOnClone() { KEY_VALUES.put("key3", "value3"); } - private static final Set MASKS = Collections.singleton("key2"); + private static final Set MASKS = Set.of("key2"); @Test public void assertKeyValuePairsWithMask() { diff --git a/core/src/test/java/jenkins/model/labels/LabelAutoCompleteSeederTest.java b/core/src/test/java/jenkins/model/labels/LabelAutoCompleteSeederTest.java index 72ea7e8c48da..cdfafb9a01a4 100644 --- a/core/src/test/java/jenkins/model/labels/LabelAutoCompleteSeederTest.java +++ b/core/src/test/java/jenkins/model/labels/LabelAutoCompleteSeederTest.java @@ -26,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.Collections; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; @@ -42,19 +41,19 @@ public class LabelAutoCompleteSeederTest { static Stream localParameters() { return Stream.of( - Arguments.of("", Collections.singletonList("")), - Arguments.of("\"", Collections.singletonList("")), - Arguments.of("\"\"", Collections.singletonList("")), - Arguments.of("freebsd", Collections.singletonList("freebsd")), - Arguments.of(" freebsd", Collections.singletonList("freebsd")), - Arguments.of("freebsd ", Collections.singletonList("")), - Arguments.of("freebsd 6", Collections.singletonList("6")), - Arguments.of("\"freebsd", Collections.singletonList("freebsd")), - Arguments.of("\"freebsd ", Collections.singletonList("freebsd ")), - Arguments.of("\"freebsd\"", Collections.singletonList("")), - Arguments.of("\"freebsd\" ", Collections.singletonList("")), - Arguments.of("\"freebsd 6", Collections.singletonList("freebsd 6")), - Arguments.of("\"freebsd 6\"", Collections.singletonList("")) + Arguments.of("", List.of("")), + Arguments.of("\"", List.of("")), + Arguments.of("\"\"", List.of("")), + Arguments.of("freebsd", List.of("freebsd")), + Arguments.of(" freebsd", List.of("freebsd")), + Arguments.of("freebsd ", List.of("")), + Arguments.of("freebsd 6", List.of("6")), + Arguments.of("\"freebsd", List.of("freebsd")), + Arguments.of("\"freebsd ", List.of("freebsd ")), + Arguments.of("\"freebsd\"", List.of("")), + Arguments.of("\"freebsd\" ", List.of("")), + Arguments.of("\"freebsd 6", List.of("freebsd 6")), + Arguments.of("\"freebsd 6\"", List.of("")) ); } diff --git a/core/src/test/java/jenkins/util/MarkFindingOutputStreamTest.java b/core/src/test/java/jenkins/util/MarkFindingOutputStreamTest.java index 928f1c4fccca..a7c8a2c9dbed 100644 --- a/core/src/test/java/jenkins/util/MarkFindingOutputStreamTest.java +++ b/core/src/test/java/jenkins/util/MarkFindingOutputStreamTest.java @@ -67,7 +67,7 @@ public void writeOneHoldOff() throws IOException { } private void assertOutput(String s) throws IOException { - assertEquals(s, baos.toString("UTF-8")); + assertEquals(s, baos.toString(StandardCharsets.UTF_8)); } private void assertCount(int n) { diff --git a/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java b/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java index e57761f33058..de82e7ae7cd4 100644 --- a/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java +++ b/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java @@ -36,7 +36,6 @@ import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -84,8 +83,8 @@ private String getTestData(String resourceName) throws IOException { private Foo createSomeFoo() { Foo foo = new Foo(); - foo.bar = new XStreamDOM("test1", Collections.singletonMap("key", "value"), "text!"); - foo.zot = new XStreamDOM("test2", Collections.singletonMap("key", "value"), Collections.singletonList(foo.bar)); + foo.bar = new XStreamDOM("test1", Map.of("key", "value"), "text!"); + foo.zot = new XStreamDOM("test2", Map.of("key", "value"), List.of(foo.bar)); return foo; } diff --git a/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java b/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java index b2c53c6e1813..f2c37445b03b 100644 --- a/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java +++ b/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java @@ -341,8 +341,8 @@ public void should_lower_case_search_string_in_case_insensitive_search() throws @Issue("JENKINS-40718") public void should_search_builds_by_build_variables() { Iterable runs = Arrays.asList( - new MockBuild(2).withBuildVariables(Collections.singletonMap("env", "dummyEnv")), - new MockBuild(1).withBuildVariables(Collections.singletonMap("env", "otherEnv"))); + new MockBuild(2).withBuildVariables(Map.of("env", "dummyEnv")), + new MockBuild(1).withBuildVariables(Map.of("env", "otherEnv"))); assertOneMatchingBuildForGivenSearchStringAndRunItems("dummyEnv", runs); } @@ -350,8 +350,8 @@ public void should_search_builds_by_build_variables() { @Issue("JENKINS-40718") public void should_search_builds_by_build_params() throws IOException { Iterable runs = Arrays.asList( - new MockBuild(2).withBuildParameters(Collections.singletonMap("env", "dummyEnv")), - new MockBuild(1).withBuildParameters(Collections.singletonMap("env", "otherEnv"))); + new MockBuild(2).withBuildParameters(Map.of("env", "dummyEnv")), + new MockBuild(1).withBuildParameters(Map.of("env", "otherEnv"))); assertOneMatchingBuildForGivenSearchStringAndRunItems("dummyEnv", runs); } @@ -359,7 +359,7 @@ public void should_search_builds_by_build_params() throws IOException { @Issue("JENKINS-40718") public void should_ignore_sensitive_parameters_in_search_builds_by_build_params() throws IOException { Iterable runs = Arrays.asList( - new MockBuild(2).withBuildParameters(Collections.singletonMap("plainPassword", "pass1plain")), + new MockBuild(2).withBuildParameters(Map.of("plainPassword", "pass1plain")), new MockBuild(1).withSensitiveBuildParameters("password", "pass1")); assertOneMatchingBuildForGivenSearchStringAndRunItems("pass1", runs); } @@ -507,8 +507,8 @@ private List buildPropertiesMapToParameterValues(Map> pluginInstalled = r.jenkins.pluginManager.install(Collections.singletonList("credentials"), true); + List> pluginInstalled = r.jenkins.pluginManager.install(List.of("credentials"), true); for (Future job : pluginInstalled) { job.get(); diff --git a/test/src/test/java/hudson/ProcTest.java b/test/src/test/java/hudson/ProcTest.java index d3e7608b8ef6..e4cc68ed7a32 100644 --- a/test/src/test/java/hudson/ProcTest.java +++ b/test/src/test/java/hudson/ProcTest.java @@ -64,7 +64,7 @@ public void run() { for (int i = 0; i < 1000; i++) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); launcher.launch().cmds("echo", str).stdout(baos).join(); - assertEquals(str, baos.toString(Charset.defaultCharset().name()).trim()); + assertEquals(str, baos.toString(Charset.defaultCharset()).trim()); } ch.close(); @@ -116,7 +116,7 @@ private void doIoPumpingTest(Launcher l) throws IOException, InterruptedExceptio ByteArrayOutputStream out = new ByteArrayOutputStream(); l.launch().cmds(ECHO_BACK_CMD).stdin(new ByteArrayInputStream("Hello".getBytes(Charset.defaultCharset()))).stdout(out).join(); - assertEquals("Hello", out.toString(Charset.defaultCharset().name())); + assertEquals("Hello", out.toString(Charset.defaultCharset())); Proc p = l.launch().cmds(ECHO_BACK_CMD).stdin(new ByteArrayInputStream("Hello".getBytes(Charset.defaultCharset()))).readStdout().start(); p.join(); diff --git a/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java b/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java index 6fa69fd52cf7..78b17c274b3c 100644 --- a/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java +++ b/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java @@ -44,6 +44,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.util.Collections; +import java.util.List; import java.util.Locale; import jenkins.security.apitoken.ApiTokenTestHelper; import jenkins.security.s2m.AdminWhitelistRule; @@ -86,7 +87,7 @@ protected Slave createNewJnlpSlave(String name) throws Exception { public void anonymousCanAlwaysLoadJARs() throws Exception { ApiTokenTestHelper.enableLegacyBehavior(); - r.jenkins.setNodes(Collections.singletonList(createNewJnlpSlave("test"))); + r.jenkins.setNodes(List.of(createNewJnlpSlave("test"))); JenkinsRule.WebClient wc = r.createWebClient(); HtmlPage p = wc.withBasicApiToken(User.getById("alice", true)).goTo("computer/test/"); @@ -110,7 +111,7 @@ public void anonymousCanAlwaysLoadJARs() throws Exception { @PresetData(DataSet.ANONYMOUS_READONLY) @Test public void anonymousCannotGetSecrets() throws Exception { - r.jenkins.setNodes(Collections.singletonList(createNewJnlpSlave("test"))); + r.jenkins.setNodes(List.of(createNewJnlpSlave("test"))); r.createWebClient().assertFails("computer/test/jenkins-agent.jnlp", HttpURLConnection.HTTP_FORBIDDEN); } @@ -119,7 +120,7 @@ public void anonymousCannotGetSecrets() throws Exception { @Test public void serviceUsingDirectSecret() throws Exception { Slave slave = createNewJnlpSlave("test"); - r.jenkins.setNodes(Collections.singletonList(slave)); + r.jenkins.setNodes(List.of(slave)); r.createWebClient().goTo("computer/test/jenkins-agent.jnlp?encrypt=true", "application/octet-stream"); String secret = slave.getComputer().getJnlpMac(); // To watch it fail: secret = secret.replace('1', '2'); diff --git a/test/src/test/java/hudson/cli/CLIActionTest.java b/test/src/test/java/hudson/cli/CLIActionTest.java index 8d2d4856368e..e26af658e174 100644 --- a/test/src/test/java/hudson/cli/CLIActionTest.java +++ b/test/src/test/java/hudson/cli/CLIActionTest.java @@ -145,7 +145,7 @@ public void encodingAndLocale() throws Exception { "-webSocket", // TODO as above "-s", j.getURL().toString()./* just checking */replaceFirst("/$", ""), "test-diagnostic"). stdout(baos).stderr(System.err).join()); - assertEquals("encoding=ISO-8859-2 locale=cs_CZ", baos.toString(Charset.forName("ISO-8859-2").name()).trim()); + assertEquals("encoding=ISO-8859-2 locale=cs_CZ", baos.toString(Charset.forName("ISO-8859-2")).trim()); // TODO test that stdout/stderr are in expected encoding (not true of -remoting mode!) // -ssh mode does not pass client locale or encoding } @@ -165,15 +165,15 @@ public void interleavedStdio() throws Exception { "-webSocket", // TODO as above "groovysh"). stdout(new TeeOutputStream(baos, System.out)).stderr(System.err).stdin(pis).start(); - while (!baos.toString(Charset.defaultCharset().name()).contains("000")) { // cannot just search for, say, "groovy:000> " since there are ANSI escapes there (cf. StringEscapeUtils.escapeJava) + while (!baos.toString(Charset.defaultCharset()).contains("000")) { // cannot just search for, say, "groovy:000> " since there are ANSI escapes there (cf. StringEscapeUtils.escapeJava) Thread.sleep(100); } pw.println("11 * 11"); - while (!baos.toString(Charset.defaultCharset().name()).contains("121")) { // ditto not "===> 121" + while (!baos.toString(Charset.defaultCharset()).contains("121")) { // ditto not "===> 121" Thread.sleep(100); } pw.println("11 * 11 * 11"); - while (!baos.toString(Charset.defaultCharset().name()).contains("1331")) { + while (!baos.toString(Charset.defaultCharset()).contains("1331")) { Thread.sleep(100); } pw.println(":q"); @@ -247,7 +247,7 @@ public void largeTransferWebSocket() throws Exception { "large-upload"). stdin(new NullInputStream(size)). stdout(baos).stderr(System.err).join()); - assertEquals("received " + size + " bytes", baos.toString(Charset.defaultCharset().name()).trim()); + assertEquals("received " + size + " bytes", baos.toString(Charset.defaultCharset()).trim()); } @TestExtension("largeTransferWebSocket") diff --git a/test/src/test/java/hudson/cli/CLIEnvVarTest.java b/test/src/test/java/hudson/cli/CLIEnvVarTest.java index eff0c985227c..ad7222f3a661 100644 --- a/test/src/test/java/hudson/cli/CLIEnvVarTest.java +++ b/test/src/test/java/hudson/cli/CLIEnvVarTest.java @@ -118,7 +118,7 @@ public void testAuthOptionWithoutEnvVars() throws Exception { "-auth", String.format("%s:%s", "admin", token), "who-am-i") ); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: admin")); + assertThat(baos.toString(Charset.defaultCharset()), containsString("Authenticated as: admin")); } } @@ -135,7 +135,7 @@ public void testWithoutEnvVarsAndWithoutAuthOption() throws Exception { "-s", r.getURL().toString(), "who-am-i") ); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: anonymous")); + assertThat(baos.toString(Charset.defaultCharset()), containsString("Authenticated as: anonymous")); } } @@ -153,7 +153,7 @@ public void testEnvVarsWithoutAuthOption() throws Exception { "-s", r.getURL().toString(), "who-am-i") ); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: admin")); + assertThat(baos.toString(Charset.defaultCharset()), containsString("Authenticated as: admin")); } } @@ -204,7 +204,7 @@ public void testAuthOptionOverridesEnvVars() throws Exception { "-auth", String.format("%s:%s", "admin", token), "who-am-i") ); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: admin")); + assertThat(baos.toString(Charset.defaultCharset()), containsString("Authenticated as: admin")); } } diff --git a/test/src/test/java/hudson/cli/CLITest.java b/test/src/test/java/hudson/cli/CLITest.java index 30b02bc7ee24..014614b9f517 100644 --- a/test/src/test/java/hudson/cli/CLITest.java +++ b/test/src/test/java/hudson/cli/CLITest.java @@ -108,7 +108,7 @@ private void doInterrupt(FreeStyleProject p, String... modeArgs) throws Exceptio args.addAll(Arrays.asList(modeArgs)); args.addAll(Arrays.asList("build", "-s", "-v", "p")); Proc proc = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds(args).stdout(new TeeOutputStream(baos, System.out)).stderr(System.err).start(); - while (!baos.toString(Charset.defaultCharset().name()).contains("Sleeping ")) { + while (!baos.toString(Charset.defaultCharset()).contains("Sleeping ")) { if (!proc.isAlive()) { throw new AssertionError("Process failed to start with " + proc.join()); } @@ -129,7 +129,7 @@ public void reportNotJenkins() throws Exception { "java", "-jar", jar.getAbsolutePath(), "-s", url, "-http", "-user", "asdf", "who-am-i" ).stdout(baos).stderr(baos).join(); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString("There's no Jenkins running at")); + assertThat(baos.toString(Charset.defaultCharset()), containsString("There's no Jenkins running at")); assertNotEquals(0, ret); // TODO -webSocket currently produces a stack trace } @@ -187,7 +187,7 @@ public void redirectToEndpointShouldBeFollowed() throws Exception { ).stdout(baos).stderr(baos).join(); //assertThat(baos.toString(), containsString("There's no Jenkins running at")); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: anonymous")); + assertThat(baos.toString(Charset.defaultCharset()), containsString("Authenticated as: anonymous")); assertEquals(0, ret); } } @@ -209,7 +209,7 @@ public void readInputAtOnce() throws Exception { .stderr(baos) .stdin(CLITest.class.getResourceAsStream("huge-stdin.txt")) .join(); - assertThat(baos.toString(Charset.defaultCharset().name()), not(containsString("java.io.IOException: Stream is closed"))); + assertThat(baos.toString(Charset.defaultCharset()), not(containsString("java.io.IOException: Stream is closed"))); assertEquals(0, ret); } } diff --git a/test/src/test/java/hudson/console/AnnotatedLargeTextTest.java b/test/src/test/java/hudson/console/AnnotatedLargeTextTest.java index 18b6f47b2e5d..61b26dfa5d08 100644 --- a/test/src/test/java/hudson/console/AnnotatedLargeTextTest.java +++ b/test/src/test/java/hudson/console/AnnotatedLargeTextTest.java @@ -57,14 +57,14 @@ public class AnnotatedLargeTextTest { @Test public void smokes() throws Exception { ByteBuffer buf = new ByteBuffer(); - PrintStream ps = new PrintStream(buf, true, StandardCharsets.UTF_8.name()); + PrintStream ps = new PrintStream(buf, true, StandardCharsets.UTF_8); ps.print("Some text.\n"); ps.print("Go back to " + TestNote.encodeTo("/root", "your home") + ".\n"); ps.print("More text.\n"); AnnotatedLargeText text = new AnnotatedLargeText<>(buf, StandardCharsets.UTF_8, true, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); text.writeLogTo(0, baos); - assertEquals("Some text.\nGo back to your home.\nMore text.\n", baos.toString(StandardCharsets.UTF_8.name())); + assertEquals("Some text.\nGo back to your home.\nMore text.\n", baos.toString(StandardCharsets.UTF_8)); StringWriter w = new StringWriter(); text.writeHtmlTo(0, w); assertEquals("Some text.\nGo back to your home.\nMore text.\n", w.toString()); @@ -87,7 +87,7 @@ public void oldDeserialization() throws Exception { AnnotatedLargeText text = new AnnotatedLargeText<>(buf, StandardCharsets.UTF_8, true, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); text.writeLogTo(0, baos); - assertEquals("hellothere\n", baos.toString(StandardCharsets.UTF_8.name())); + assertEquals("hellothere\n", baos.toString(StandardCharsets.UTF_8)); StringWriter w = new StringWriter(); text.writeHtmlTo(0, w); assertEquals("hellothere\n", w.toString()); @@ -125,7 +125,7 @@ public void badMac() throws Exception { AnnotatedLargeText text = new AnnotatedLargeText<>(buf, StandardCharsets.UTF_8, true, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); text.writeLogTo(0, baos); - assertEquals("Go back to your home.\n", baos.toString(StandardCharsets.UTF_8.name())); + assertEquals("Go back to your home.\n", baos.toString(StandardCharsets.UTF_8)); StringWriter w = new StringWriter(); text.writeHtmlTo(0, w); assertEquals("Go back to your home.\n", w.toString()); diff --git a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java index 25f37bd9bf8b..fc03efc4e495 100644 --- a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java @@ -17,7 +17,7 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; -import java.util.Collections; +import java.util.List; import jenkins.model.Jenkins; import jenkins.security.apitoken.ApiTokenTestHelper; import org.junit.Rule; @@ -80,7 +80,7 @@ public void noAccessForNonAdmin() throws Exception { WebRequest request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); NameValuePair param = new NameValuePair("no", "true"); - request.setRequestParameters(Collections.singletonList(param)); + request.setRequestParameters(List.of(param)); HudsonHomeDiskUsageMonitor mon = HudsonHomeDiskUsageMonitor.get(); @@ -96,7 +96,7 @@ public void noAccessForNonAdmin() throws Exception { wc.withBasicApiToken(administrator); request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); - request.setRequestParameters(Collections.singletonList(param)); + request.setRequestParameters(List.of(param)); p = wc.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode()); assertFalse(mon.isEnabled()); diff --git a/test/src/test/java/hudson/diagnosis/OldDataMonitorTest.java b/test/src/test/java/hudson/diagnosis/OldDataMonitorTest.java index d44e3ec479c5..50eac0447fd3 100644 --- a/test/src/test/java/hudson/diagnosis/OldDataMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/OldDataMonitorTest.java @@ -36,6 +36,7 @@ import java.io.IOException; import java.lang.ref.WeakReference; import java.util.Collections; +import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -68,7 +69,7 @@ public class OldDataMonitorTest { OldDataMonitor odm = OldDataMonitor.get(r.jenkins); FreeStyleProject p = r.jenkins.getItemByFullName("busted", FreeStyleProject.class); assertNotNull(p); - assertEquals(Collections.singleton(p), odm.getData().keySet()); + assertEquals(Set.of(p), odm.getData().keySet()); odm.doDiscard(null, null); assertEquals(Collections.emptySet(), odm.getData().keySet()); // did not manage to save p, but at least we are not holding onto a reference to it anymore @@ -83,7 +84,7 @@ public class OldDataMonitorTest { r.jenkins.getQueue().clearLeftItems(); p._getRuns().purgeCache(); b = p.getBuildByNumber(1); - assertEquals(Collections.singleton(b), OldDataMonitor.get(r.jenkins).getData().keySet()); + assertEquals(Set.of(b), OldDataMonitor.get(r.jenkins).getData().keySet()); WeakReference ref = new WeakReference<>(b); b = null; MemoryAssert.assertGC(ref, true); @@ -145,7 +146,7 @@ public Void call() { p.delete(); OldDataMonitor.report(build, (String) null); - assertEquals(Collections.singleton(build), odm.getData().keySet()); + assertEquals(Set.of(build), odm.getData().keySet()); odm.doDiscard(null, null); assertEquals(Collections.emptySet(), odm.getData().keySet()); diff --git a/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java b/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java index 00d95497ab19..3b8c71fdf45b 100644 --- a/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java @@ -30,7 +30,7 @@ import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.util.NameValuePair; import java.net.URL; -import java.util.Collections; +import java.util.List; import jenkins.model.JenkinsLocationConfiguration; import org.junit.Before; import org.junit.Rule; @@ -84,7 +84,7 @@ public void evaluate() throws Throwable { request.setAdditionalHeader("Referer", j.getURL() + "manage"); // As the context was already set inside the referer, adding another one will fail - request.setRequestParameters(Collections.singletonList(new NameValuePair("testWithContext", "true"))); + request.setRequestParameters(List.of(new NameValuePair("testWithContext", "true"))); assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); } }); @@ -138,7 +138,7 @@ public void evaluate() throws Throwable { assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); // When testing with the context, it will be OK, allowing to display an additional message - request.setRequestParameters(Collections.singletonList(new NameValuePair("testWithContext", "true"))); + request.setRequestParameters(List.of(new NameValuePair("testWithContext", "true"))); wc.getPage(request); } }); @@ -161,7 +161,7 @@ public void evaluate() throws Throwable { assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); - request.setRequestParameters(Collections.singletonList(new NameValuePair("testWithContext", "true"))); + request.setRequestParameters(List.of(new NameValuePair("testWithContext", "true"))); assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); } }); @@ -182,7 +182,7 @@ public void evaluate() throws Throwable { wc.getPage(request); // adding the context does not have any impact as there is no configured context - request.setRequestParameters(Collections.singletonList(new NameValuePair("testWithContext", "true"))); + request.setRequestParameters(List.of(new NameValuePair("testWithContext", "true"))); wc.getPage(request); } }); @@ -272,7 +272,7 @@ public void evaluate() throws Throwable { assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); // When testing with the context, it will be OK, allowing to display an additional message - request.setRequestParameters(Collections.singletonList(new NameValuePair("testWithContext", "true"))); + request.setRequestParameters(List.of(new NameValuePair("testWithContext", "true"))); wc.getPage(request); } }); diff --git a/test/src/test/java/hudson/model/AbstractBuildTest.java b/test/src/test/java/hudson/model/AbstractBuildTest.java index 97ae91a78c18..237861582cc0 100644 --- a/test/src/test/java/hudson/model/AbstractBuildTest.java +++ b/test/src/test/java/hudson/model/AbstractBuildTest.java @@ -50,7 +50,6 @@ import hudson.util.OneShotEvent; import java.io.IOException; import java.util.Arrays; -import java.util.Collections; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.TimeUnit; @@ -203,7 +202,7 @@ public void culprits() throws Exception { // 4th build, unstable. culprit list should continue scm.addChange().withAuthor("dave"); - p.getBuildersList().replaceBy(Collections.singleton(new UnstableBuilder())); + p.getBuildersList().replaceBy(Set.of(new UnstableBuilder())); b = j.buildAndAssertStatus(Result.UNSTABLE, p); assertCulprits(b, "bob", "charlie", "dave"); diff --git a/test/src/test/java/hudson/model/AbstractItemTest.java b/test/src/test/java/hudson/model/AbstractItemTest.java index f227238e2e46..1f6c709027c0 100644 --- a/test/src/test/java/hudson/model/AbstractItemTest.java +++ b/test/src/test/java/hudson/model/AbstractItemTest.java @@ -18,7 +18,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.Collections; +import java.util.List; import jenkins.model.Jenkins; import jenkins.model.ProjectNamingStrategy; import org.apache.commons.io.FileUtils; @@ -114,14 +114,14 @@ public void renameViaRestApi() throws Exception { WebClient w = j.createWebClient(); WebRequest wr = new WebRequest(w.createCrumbedUrl(p.getUrl() + "confirmRename"), HttpMethod.POST); - wr.setRequestParameters(Collections.singletonList(new NameValuePair("newName", "bar"))); + wr.setRequestParameters(List.of(new NameValuePair("newName", "bar"))); w.login("alice", "alice"); Page page = w.getPage(wr); assertThat(getPath(page.getUrl()), equalTo(p.getUrl())); assertThat(p.getName(), equalTo("bar")); wr = new WebRequest(w.createCrumbedUrl(p.getUrl() + "confirmRename"), HttpMethod.POST); - wr.setRequestParameters(Collections.singletonList(new NameValuePair("newName", "baz"))); + wr.setRequestParameters(List.of(new NameValuePair("newName", "baz"))); w.login("bob", "bob"); w.setThrowExceptionOnFailingStatusCode(false); diff --git a/test/src/test/java/hudson/model/AbstractProjectTest.java b/test/src/test/java/hudson/model/AbstractProjectTest.java index e3d0f3e23df2..200695af1cfa 100644 --- a/test/src/test/java/hudson/model/AbstractProjectTest.java +++ b/test/src/test/java/hudson/model/AbstractProjectTest.java @@ -71,9 +71,9 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.ResourceBundle; +import java.util.Set; import java.util.Vector; import java.util.concurrent.Future; import jenkins.model.Jenkins; @@ -514,10 +514,10 @@ public boolean isApplicable(hudson.model.Item item) { public void upstreamDownstreamExportApi() throws Exception { FreeStyleProject us = j.createFreeStyleProject("upstream-project"); FreeStyleProject ds = j.createFreeStyleProject("downstream-project"); - us.getPublishersList().add(new BuildTrigger(Collections.singleton(ds), Result.SUCCESS)); + us.getPublishersList().add(new BuildTrigger(Set.of(ds), Result.SUCCESS)); j.jenkins.rebuildDependencyGraph(); - assertEquals(Collections.singletonList(ds), us.getDownstreamProjects()); - assertEquals(Collections.singletonList(us), ds.getUpstreamProjects()); + assertEquals(List.of(ds), us.getDownstreamProjects()); + assertEquals(List.of(us), ds.getUpstreamProjects()); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.READ).everywhere().toEveryone(). diff --git a/test/src/test/java/hudson/model/CauseTest.java b/test/src/test/java/hudson/model/CauseTest.java index 90737294dca6..27e95d675f65 100644 --- a/test/src/test/java/hudson/model/CauseTest.java +++ b/test/src/test/java/hudson/model/CauseTest.java @@ -105,21 +105,21 @@ public class CauseTest { Cause causeA = new Cause.UserIdCause(null); causeA.print(listener); - assertEquals("Started by user unknown or anonymous", baos.toString(Charset.defaultCharset().name()).trim()); + assertEquals("Started by user unknown or anonymous", baos.toString(Charset.defaultCharset()).trim()); baos.reset(); //SYSTEM userid - getDisplayName() should be SYSTEM Cause causeB = new Cause.UserIdCause(); causeB.print(listener); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString("SYSTEM")); + assertThat(baos.toString(Charset.defaultCharset()), containsString("SYSTEM")); baos.reset(); //unknown userid - print unknown or anonymous Cause causeC = new Cause.UserIdCause("abc123"); causeC.print(listener); - assertEquals("Started by user unknown or anonymous", baos.toString(Charset.defaultCharset().name()).trim()); + assertEquals("Started by user unknown or anonymous", baos.toString(Charset.defaultCharset()).trim()); baos.reset(); //More or less standard operation @@ -128,7 +128,7 @@ public class CauseTest { Cause causeD = new Cause.UserIdCause(user.getId()); causeD.print(listener); - assertThat(baos.toString(Charset.defaultCharset().name()), containsString(user.getDisplayName())); + assertThat(baos.toString(Charset.defaultCharset()), containsString(user.getDisplayName())); baos.reset(); } diff --git a/test/src/test/java/hudson/model/ComputerConfigDotXmlTest.java b/test/src/test/java/hudson/model/ComputerConfigDotXmlTest.java index 9d79f0f6c788..d5c3cbfdf207 100644 --- a/test/src/test/java/hudson/model/ComputerConfigDotXmlTest.java +++ b/test/src/test/java/hudson/model/ComputerConfigDotXmlTest.java @@ -219,7 +219,7 @@ public void nodeNameReferencesParentDir() throws Exception { FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(req)); assertThat(e.getStatusCode(), equalTo(400)); File configDotXml = new File(rule.jenkins.getRootDir(), "config.xml"); - String configDotXmlContents = new String(Files.readAllBytes(configDotXml.toPath()), StandardCharsets.UTF_8); + String configDotXmlContents = Files.readString(configDotXml.toPath(), StandardCharsets.UTF_8); assertThat(configDotXmlContents, not(containsString("../"))); } diff --git a/test/src/test/java/hudson/model/DependencyGraphTest.java b/test/src/test/java/hudson/model/DependencyGraphTest.java index b54cee82b9bc..5c3c705579c2 100644 --- a/test/src/test/java/hudson/model/DependencyGraphTest.java +++ b/test/src/test/java/hudson/model/DependencyGraphTest.java @@ -33,7 +33,6 @@ import hudson.tasks.BuildTrigger; import hudson.tasks.MailMessageIdAction; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import jenkins.model.DependencyDeclarer; @@ -62,7 +61,7 @@ public void testTriggerJob() throws Exception { down1 = j.createFreeStyleProject(), down2 = j.createFreeStyleProject(); // Add one standard downstream job: p.getPublishersList().add( - new BuildTrigger(Collections.singletonList(down1), Result.SUCCESS)); + new BuildTrigger(List.of(down1), Result.SUCCESS)); // Add one downstream job with custom Dependency impl: p.getBuildersList().add(new TestDeclarer(Result.UNSTABLE, down2)); j.jenkins.rebuildDependencyGraph(); diff --git a/test/src/test/java/hudson/model/FileParameterValueTest.java b/test/src/test/java/hudson/model/FileParameterValueTest.java index 3b1452a93a76..84e71a9a3d09 100644 --- a/test/src/test/java/hudson/model/FileParameterValueTest.java +++ b/test/src/test/java/hudson/model/FileParameterValueTest.java @@ -41,7 +41,6 @@ import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; @@ -68,7 +67,7 @@ public void fileParameter_cannotCreateFile_outsideOfBuildFolder() throws Excepti FilePath root = j.jenkins.getRootPath(); FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("../../../../../root-level.txt", null) ))); @@ -108,7 +107,7 @@ public void fileParameter_cannotCreateFile_outsideOfBuildFolder_SEC1424() throws FilePath root = j.jenkins.getRootPath(); FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("dir/../../../pwned", null) ))); @@ -135,7 +134,7 @@ public void fileParameter_cannotCreateFile_outsideOfBuildFolder_LeadingDoubleDot FilePath root = j.jenkins.getRootPath(); FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("../pwned", null) ))); @@ -173,7 +172,7 @@ public void fileParameter_cannotCreateFile_outsideOfBuildFolder_backslashEdition FilePath root = j.jenkins.getRootPath(); FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("..\\..\\..\\..\\..\\root-level.txt", null) ))); @@ -204,7 +203,7 @@ public void fileParameter_withSingleDot() throws Exception { // this case was not working even before the patch FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition(".", null) ))); @@ -232,7 +231,7 @@ public void fileParameter_withDoubleDot() throws Exception { // this case was not working even before the patch FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("..", null) ))); @@ -262,7 +261,7 @@ public void fileParameter_cannotEraseFile_outsideOfBuildFolder() throws Exceptio FilePath root = j.jenkins.getRootPath(); FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("../../../../../root-level.txt", null) ))); @@ -333,7 +332,7 @@ public void fileParameter_canStillUse_internalHierarchy() throws Exception { @Test public void fileParameter_canStillUse_doubleDotsInFileName() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("weird..name.txt", null) ))); @@ -361,7 +360,7 @@ public void fileParameter_canStillUse_doubleDotsInFileName() throws Exception { @Test public void fileParameter_canStillUse_TildeInFileName() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new FileParameterDefinition("~name", null) ))); diff --git a/test/src/test/java/hudson/model/FingerprintCleanupThreadTest.java b/test/src/test/java/hudson/model/FingerprintCleanupThreadTest.java index a910f69c8cde..d6c924984a86 100644 --- a/test/src/test/java/hudson/model/FingerprintCleanupThreadTest.java +++ b/test/src/test/java/hudson/model/FingerprintCleanupThreadTest.java @@ -41,7 +41,6 @@ import java.io.File; import java.io.IOException; import java.io.PrintStream; -import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; @@ -73,7 +72,7 @@ public void testDoesNotLogUnimportantExcessiveLogMessage() throws IOException { configureLocalTestStorage(new TestFingerprint(true)); FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread(); cleanupThread.execute(testTaskListener); - String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name()); + String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset()); assertFalse("Should not have logged unimportant, excessive message.", logOutput.contains("possibly trimming")); } @@ -84,7 +83,7 @@ public void testFingerprintFileIsEmpty() throws IOException { configureLocalTestStorage(new TestFingerprint(false)); FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread(); cleanupThread.execute(testTaskListener); - String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name()); + String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset()); assertFalse("Should have deleted obsolete file.", fpFile.toFile().exists()); } @@ -101,7 +100,7 @@ public void testNoFingerprintsDir() throws IOException { configureLocalTestStorage(new TestFingerprint()); FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread(); cleanupThread.execute(testTaskListener); - String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name()); + String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset()); assertTrue("Should have done nothing.", logOutput.startsWith("Cleaned up 0 records")); } @@ -116,7 +115,7 @@ public void testBlockingFacetBlocksDeletion() throws IOException { configureLocalTestStorage(fp); FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread(); cleanupThread.execute(testTaskListener); - String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name()); + String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset()); assertThat(logOutput, containsString("blocked deletion of")); } @@ -222,15 +221,7 @@ private void createTestDir() throws IOException { private static class TestTaskListener implements TaskListener { private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - private final PrintStream logStream; - - { - try { - logStream = new PrintStream(outputStream, false, Charset.defaultCharset().name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } - } + private final PrintStream logStream = new PrintStream(outputStream, false, Charset.defaultCharset()); @NonNull @Override diff --git a/test/src/test/java/hudson/model/FingerprintTest.java b/test/src/test/java/hudson/model/FingerprintTest.java index 28caefa86f45..cbc6ee91afb5 100644 --- a/test/src/test/java/hudson/model/FingerprintTest.java +++ b/test/src/test/java/hudson/model/FingerprintTest.java @@ -56,11 +56,11 @@ import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; @@ -650,7 +650,7 @@ private void setJobPermissionsOnce(Job job, String username, @NonNull Perm assertThat("Cannot assign the property twice", job.getProperty(AuthorizationMatrixProperty.class), nullValue()); Map> permissions = new HashMap<>(); - HashSet userSpec = new HashSet<>(Collections.singletonList(username)); + HashSet userSpec = new HashSet<>(List.of(username)); for (Permission p : s) { permissions.put(p, userSpec); diff --git a/test/src/test/java/hudson/model/JobTest.java b/test/src/test/java/hudson/model/JobTest.java index f0d764be1570..18593a10288b 100644 --- a/test/src/test/java/hudson/model/JobTest.java +++ b/test/src/test/java/hudson/model/JobTest.java @@ -377,7 +377,7 @@ private static void tryConfigDotXml(JenkinsRule.WebClient wc, int status, String FreeStyleBuild b2 = p2.getBuilds().getLastBuild(); ByteArrayOutputStream out = new ByteArrayOutputStream(); b2.getLogText().writeRawLogTo(0, out); - final String oldB2Log = out.toString(Charset.defaultCharset().name()); + final String oldB2Log = out.toString(Charset.defaultCharset()); assertTrue(b2.getArtifactManager().root().child("hello.txt").exists()); f.renameTo("something-else"); @@ -394,7 +394,7 @@ private static void tryConfigDotXml(JenkinsRule.WebClient wc, int status, String assertNotNull(b2); out = new ByteArrayOutputStream(); b2.getLogText().writeRawLogTo(0, out); - final String newB2Log = out.toString(Charset.defaultCharset().name()); + final String newB2Log = out.toString(Charset.defaultCharset()); assertEquals(oldB2Log, newB2Log); assertTrue(b2.getArtifactManager().root().child("hello.txt").exists()); diff --git a/test/src/test/java/hudson/model/ListViewTest.java b/test/src/test/java/hudson/model/ListViewTest.java index e21a81e2e60e..72a0419fc07d 100644 --- a/test/src/test/java/hudson/model/ListViewTest.java +++ b/test/src/test/java/hudson/model/ListViewTest.java @@ -142,7 +142,7 @@ private void checkLinkFromItemExistsAndIsValid(Item item, ItemGroup ig, Item top v.setIncludeRegex(".*"); v.setRecurse(true); // Note: did not manage to reproduce CCE until I changed expand to use ‘for (TopLevelItem item : items)’ rather than ‘for (Item item : items)’; perhaps a compiler-specific issue? - assertEquals(Collections.singletonList(mp), v.getItems()); + assertEquals(List.of(mp), v.getItems()); } @Issue("JENKINS-18680") @@ -247,7 +247,7 @@ private void checkLinkFromItemExistsAndIsValid(Item item, ItemGroup ig, Item top try (ACLContext acl = ACL.as(User.getOrCreateByIdOrFullName("alice"))) { p.renameTo("p2"); } - assertEquals(Collections.singletonList(p), v.getItems()); + assertEquals(List.of(p), v.getItems()); } @Issue("JENKINS-41128") @@ -338,7 +338,7 @@ private void checkLinkFromItemExistsAndIsValid(Item item, ItemGroup ig, Item top FreeStyleProject p3 = f1.createProject(FreeStyleProject.class, "p3"); FreeStyleProject p4 = f2.createProject(FreeStyleProject.class, "p4"); ListView lv = new ListView("view", Jenkins.get()); - lv.setJobFilters(Collections.singletonList(new AllFilter())); + lv.setJobFilters(List.of(new AllFilter())); lv.setRecurse(false); assertThat(lv.getItems(), containsInAnyOrder(f1, f2, p1, p2)); lv.setRecurse(true); diff --git a/test/src/test/java/hudson/model/NodeTest.java b/test/src/test/java/hudson/model/NodeTest.java index 9fe57c86875e..6558dc191923 100644 --- a/test/src/test/java/hudson/model/NodeTest.java +++ b/test/src/test/java/hudson/model/NodeTest.java @@ -58,9 +58,9 @@ import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.GregorianCalendar; import java.util.List; +import java.util.Map; import jenkins.model.Jenkins; import jenkins.security.QueueItemAuthenticatorConfiguration; import org.junit.Before; @@ -222,7 +222,7 @@ public void testCanTake() throws Exception { j.jenkins.setSecurityRealm(realm); realm.createAccount("John", ""); notTake = false; - QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap(project.getFullName(), user.impersonate()))); + QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Map.of(project.getFullName(), user.impersonate()))); assertNotNull("Node should not take project because user does not have build permission.", node.canTake(item)); message = Messages._Node_LackingBuildPermission(item.authenticate2().getName(), node.getNodeName()).toString(); assertEquals("Cause of blockage should be build permission label.", message, node.canTake(item).getShortDescription()); diff --git a/test/src/test/java/hudson/model/ParametersAction2Test.java b/test/src/test/java/hudson/model/ParametersAction2Test.java index 48f730d97f57..7e36a5762c5a 100644 --- a/test/src/test/java/hudson/model/ParametersAction2Test.java +++ b/test/src/test/java/hudson/model/ParametersAction2Test.java @@ -128,7 +128,7 @@ public void parametersDefinitionChange() throws Exception { // remove bar and undef from parameters definition p.removeProperty(ParametersDefinitionProperty.class); - p.addProperty(new ParametersDefinitionProperty(Collections.singletonList( + p.addProperty(new ParametersDefinitionProperty(List.of( new StringParameterDefinition("foo", "foo")))); assertEquals("the build still have 2 parameters", 2, build.getAction(ParametersAction.class).getParameters().size()); diff --git a/test/src/test/java/hudson/model/ProjectTest.java b/test/src/test/java/hudson/model/ProjectTest.java index 8d2318fd1149..817ff8250e66 100644 --- a/test/src/test/java/hudson/model/ProjectTest.java +++ b/test/src/test/java/hudson/model/ProjectTest.java @@ -84,6 +84,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -380,7 +381,7 @@ public void testGetCauseOfBlockage() throws Exception { FreeStyleProject downstream = j.createFreeStyleProject("project-downstream"); downstream.getBuildersList().add(Functions.isWindows() ? new BatchFile("ping -n 10 127.0.0.1 >nul") : new Shell("sleep 10")); - p.getPublishersList().add(new BuildTrigger(Collections.singleton(downstream), Result.SUCCESS)); + p.getPublishersList().add(new BuildTrigger(Set.of(downstream), Result.SUCCESS)); Jenkins.get().rebuildDependencyGraph(); p.setBlockBuildWhenDownstreamBuilding(true); QueueTaskFuture b2 = waitForStart(downstream); diff --git a/test/src/test/java/hudson/model/QueueTest.java b/test/src/test/java/hudson/model/QueueTest.java index 152c606026c0..efae2285e24e 100644 --- a/test/src/test/java/hudson/model/QueueTest.java +++ b/test/src/test/java/hudson/model/QueueTest.java @@ -446,7 +446,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen r.jenkins.setNumExecutors(0); r.jenkins.setNodes(Collections.emptyList()); MatrixProject m = r.jenkins.createProject(MatrixProject.class, "p"); - m.setAxes(new AxisList(new LabelAxis("label", Collections.singletonList("remote")))); + m.setAxes(new AxisList(new LabelAxis("label", List.of("remote")))); MatrixBuild build; try { build = m.scheduleBuild2(0).get(60, TimeUnit.SECONDS); @@ -701,7 +701,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen */ @Test public void accessControl() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); - QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap(p.getFullName(), alice))); + QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Map.of(p.getFullName(), alice))); p.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { @@ -728,7 +728,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen DumbSlave s2 = r.createSlave(); FreeStyleProject p = r.createFreeStyleProject(); - QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap(p.getFullName(), alice))); + QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Map.of(p.getFullName(), alice))); p.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { @@ -886,8 +886,8 @@ public void run() { projectC.getBuildersList().add(new SleepBuilder(10000)); projectC.setBlockBuildWhenUpstreamBuilding(true); - projectA.getPublishersList().add(new BuildTrigger(Collections.singletonList(projectB), Result.SUCCESS)); - projectB.getPublishersList().add(new BuildTrigger(Collections.singletonList(projectC), Result.SUCCESS)); + projectA.getPublishersList().add(new BuildTrigger(List.of(projectB), Result.SUCCESS)); + projectB.getPublishersList().add(new BuildTrigger(List.of(projectC), Result.SUCCESS)); final QueueTaskFuture taskA = projectA.scheduleBuild2(0, new TimerTriggerCause()); Thread.sleep(1000); @@ -1032,8 +1032,8 @@ public void queueApiOutputShouldBeFilteredByUserPermission() throws Exception { FreeStyleProject project = r.createFreeStyleProject("project"); Map> permissions = new HashMap<>(); - permissions.put(Item.READ, Collections.singleton("bob")); - permissions.put(Item.DISCOVER, Collections.singleton("james")); + permissions.put(Item.READ, Set.of("bob")); + permissions.put(Item.DISCOVER, Set.of("james")); AuthorizationMatrixProperty prop1 = new AuthorizationMatrixProperty(permissions); project.addProperty(prop1); project.getBuildersList().add(new SleepBuilder(10)); diff --git a/test/src/test/java/hudson/model/RunParameterDefinitionTest.java b/test/src/test/java/hudson/model/RunParameterDefinitionTest.java index f31f8cd66c57..11a7662bac8d 100644 --- a/test/src/test/java/hudson/model/RunParameterDefinitionTest.java +++ b/test/src/test/java/hudson/model/RunParameterDefinitionTest.java @@ -32,7 +32,7 @@ import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.util.LogTaskListener; -import java.util.Collections; +import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Rule; @@ -93,16 +93,16 @@ public void testNULLFilter() throws Exception { FreeStyleProject project = j.createFreeStyleProject("project"); FreeStyleBuild successfulBuild = j.buildAndAssertSuccess(project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.UNSTABLE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.UNSTABLE))); FreeStyleBuild unstableBuild = j.buildAndAssertStatus(Result.UNSTABLE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.FAILURE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.FAILURE))); FreeStyleBuild failedBuild = j.buildAndAssertStatus(Result.FAILURE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.NOT_BUILT))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.NOT_BUILT))); FreeStyleBuild notBuiltBuild = j.buildAndAssertStatus(Result.NOT_BUILT, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.ABORTED))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.ABORTED))); FreeStyleBuild abortedBuild = j.buildAndAssertStatus(Result.ABORTED, project); FreeStyleProject paramProject = j.createFreeStyleProject("paramProject"); @@ -125,16 +125,16 @@ public void testALLFilter() throws Exception { FreeStyleProject project = j.createFreeStyleProject("project"); FreeStyleBuild successfulBuild = j.buildAndAssertSuccess(project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.UNSTABLE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.UNSTABLE))); FreeStyleBuild unstableBuild = j.buildAndAssertStatus(Result.UNSTABLE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.FAILURE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.FAILURE))); FreeStyleBuild failedBuild = j.buildAndAssertStatus(Result.FAILURE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.NOT_BUILT))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.NOT_BUILT))); FreeStyleBuild notBuiltBuild = j.buildAndAssertStatus(Result.NOT_BUILT, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.ABORTED))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.ABORTED))); FreeStyleBuild abortedBuild = j.buildAndAssertStatus(Result.ABORTED, project); FreeStyleProject paramProject = j.createFreeStyleProject("paramProject"); @@ -156,16 +156,16 @@ public void testCOMPLETEDFilter() throws Exception { FreeStyleProject project = j.createFreeStyleProject("project"); FreeStyleBuild successfulBuild = j.buildAndAssertSuccess(project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.UNSTABLE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.UNSTABLE))); FreeStyleBuild unstableBuild = j.buildAndAssertStatus(Result.UNSTABLE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.FAILURE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.FAILURE))); FreeStyleBuild failedBuild = j.buildAndAssertStatus(Result.FAILURE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.NOT_BUILT))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.NOT_BUILT))); FreeStyleBuild notBuiltBuild = j.buildAndAssertStatus(Result.NOT_BUILT, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.ABORTED))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.ABORTED))); FreeStyleBuild abortedBuild = j.buildAndAssertStatus(Result.ABORTED, project); FreeStyleProject paramProject = j.createFreeStyleProject("paramProject"); @@ -187,16 +187,16 @@ public void testSUCCESSFULFilter() throws Exception { FreeStyleProject project = j.createFreeStyleProject("project"); FreeStyleBuild successfulBuild = j.buildAndAssertSuccess(project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.UNSTABLE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.UNSTABLE))); FreeStyleBuild unstableBuild = j.buildAndAssertStatus(Result.UNSTABLE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.FAILURE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.FAILURE))); FreeStyleBuild failedBuild = j.buildAndAssertStatus(Result.FAILURE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.NOT_BUILT))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.NOT_BUILT))); FreeStyleBuild notBuiltBuild = j.buildAndAssertStatus(Result.NOT_BUILT, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.ABORTED))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.ABORTED))); FreeStyleBuild abortedBuild = j.buildAndAssertStatus(Result.ABORTED, project); FreeStyleProject paramProject = j.createFreeStyleProject("paramProject"); @@ -219,16 +219,16 @@ public void testSTABLEFilter() throws Exception { FreeStyleProject project = j.createFreeStyleProject("project"); FreeStyleBuild successfulBuild = j.buildAndAssertSuccess(project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.UNSTABLE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.UNSTABLE))); FreeStyleBuild unstableBuild = j.buildAndAssertStatus(Result.UNSTABLE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.FAILURE))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.FAILURE))); FreeStyleBuild failedBuild = j.buildAndAssertStatus(Result.FAILURE, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.NOT_BUILT))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.NOT_BUILT))); FreeStyleBuild notBuiltBuild = j.buildAndAssertStatus(Result.NOT_BUILT, project); - project.getPublishersList().replaceBy(Collections.singleton(new ResultPublisher(Result.ABORTED))); + project.getPublishersList().replaceBy(Set.of(new ResultPublisher(Result.ABORTED))); FreeStyleBuild abortedBuild = j.buildAndAssertStatus(Result.ABORTED, project); FreeStyleProject paramProject = j.createFreeStyleProject("paramProject"); diff --git a/test/src/test/java/hudson/model/SlaveTest.java b/test/src/test/java/hudson/model/SlaveTest.java index 5f4216790723..d9654bf0d0f2 100644 --- a/test/src/test/java/hudson/model/SlaveTest.java +++ b/test/src/test/java/hudson/model/SlaveTest.java @@ -177,7 +177,7 @@ private void assertJnlpJarUrlIsAllowed(@NonNull Slave slave, @NonNull String url // Access from a Web client JenkinsRule.WebClient client = j.createWebClient(); - assertEquals(200, client.getPage(client.getContextPath() + "jnlpJars/" + URLEncoder.encode(url, "UTF-8")).getWebResponse().getStatusCode()); + assertEquals(200, client.getPage(client.getContextPath() + "jnlpJars/" + URLEncoder.encode(url, StandardCharsets.UTF_8)).getWebResponse().getStatusCode()); assertEquals(200, client.getPage(jnlpJar.getURL()).getWebResponse().getStatusCode()); } diff --git a/test/src/test/java/hudson/model/UsageStatisticsTest.java b/test/src/test/java/hudson/model/UsageStatisticsTest.java index 7ff80714065f..03c598434fea 100644 --- a/test/src/test/java/hudson/model/UsageStatisticsTest.java +++ b/test/src/test/java/hudson/model/UsageStatisticsTest.java @@ -188,7 +188,7 @@ private JSONObject sortJobTypes(JSONObject object) { private void compareWithFile(String fileName, Object object) throws IOException, URISyntaxException { Class clazz = this.getClass(); - String fileContent = new String(Files.readAllBytes(Paths.get(clazz.getResource(clazz.getSimpleName() + "/" + fileName).toURI())), StandardCharsets.UTF_8); + String fileContent = Files.readString(Paths.get(clazz.getResource(clazz.getSimpleName() + "/" + fileName).toURI()), StandardCharsets.UTF_8); fileContent = fileContent.replace("JVMVENDOR", System.getProperty("java.vm.vendor")); fileContent = fileContent.replace("JVMNAME", System.getProperty("java.vm.name")); fileContent = fileContent.replace("JVMVERSION", System.getProperty("java.version")); diff --git a/test/src/test/java/hudson/model/UserTest.java b/test/src/test/java/hudson/model/UserTest.java index a3e35cf2f6c1..09cb2b0ac5dc 100644 --- a/test/src/test/java/hudson/model/UserTest.java +++ b/test/src/test/java/hudson/model/UserTest.java @@ -66,6 +66,7 @@ import java.util.Collections; import java.util.List; import java.util.Locale; +import java.util.Set; import jenkins.model.IdStrategy; import jenkins.model.Jenkins; import jenkins.security.ApiTokenProperty; @@ -622,7 +623,7 @@ public UserDetails loadUserByUsername2(String username) throws UsernameNotFoundE } catch (IOException x) { throw new RuntimeException(x); } - return new org.springframework.security.core.userdetails.User(canonicalName, "", true, true, true, true, Collections.singleton(AUTHENTICATED_AUTHORITY2)); + return new org.springframework.security.core.userdetails.User(canonicalName, "", true, true, true, true, Set.of(AUTHENTICATED_AUTHORITY2)); } } diff --git a/test/src/test/java/hudson/model/ViewTest.java b/test/src/test/java/hudson/model/ViewTest.java index dc0fef808160..a41006fa6037 100644 --- a/test/src/test/java/hudson/model/ViewTest.java +++ b/test/src/test/java/hudson/model/ViewTest.java @@ -75,9 +75,9 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -382,7 +382,7 @@ public void testGetComputers() throws Exception { MatrixProject matrixJob = j.jenkins.createProject(MatrixProject.class, "matrix"); view1.add(matrixJob); matrixJob.setAxes(new AxisList( - new LabelAxis("label", Collections.singletonList("label1")) + new LabelAxis("label", List.of("label1")) )); FreeStyleProject noLabelJob = j.createFreeStyleProject("not-assigned-label"); @@ -888,7 +888,7 @@ public void shouldNotAllowInconsistentViewName() throws IOException { JenkinsRule.WebClient wc = j.createWebClient(); WebRequest req = new WebRequest(wc.createCrumbedUrl("createView"), HttpMethod.POST); req.setEncodingType(FormEncodingType.URL_ENCODED); - req.setRequestBody("name=ViewName&mode=hudson.model.ListView&json=" + URLEncoder.encode("{\"mode\":\"hudson.model.ListView\",\"name\":\"DifferentViewName\"}", "UTF-8")); + req.setRequestBody("name=ViewName&mode=hudson.model.ListView&json=" + URLEncoder.encode("{\"mode\":\"hudson.model.ListView\",\"name\":\"DifferentViewName\"}", StandardCharsets.UTF_8)); wc.getPage(req); assertNull(j.jenkins.getView("DifferentViewName")); assertNotNull(j.jenkins.getView("ViewName")); diff --git a/test/src/test/java/hudson/model/queue/LoadPredictorTest.java b/test/src/test/java/hudson/model/queue/LoadPredictorTest.java index 74b283234200..275c3fed7d52 100644 --- a/test/src/test/java/hudson/model/queue/LoadPredictorTest.java +++ b/test/src/test/java/hudson/model/queue/LoadPredictorTest.java @@ -40,7 +40,6 @@ import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.GregorianCalendar; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -61,7 +60,7 @@ public class LoadPredictorTest { public static class LoadPredictorImpl extends LoadPredictor { @Override public Iterable predict(MappingWorksheet plan, Computer computer, long start, long end) { - return Collections.singletonList(new FutureLoad(start + 5000, end - (start + 5000), 1)); + return List.of(new FutureLoad(start + 5000, end - (start + 5000), 1)); } } @@ -77,13 +76,13 @@ public Iterable predict(MappingWorksheet plan, Computer computer, lo public void test1() throws Exception { Task t = mock(Task.class); when(t.getEstimatedDuration()).thenReturn(10000L); - when(t.getSubTasks()).thenReturn((Collection) Collections.singletonList(t)); + when(t.getSubTasks()).thenReturn((Collection) List.of(t)); Computer c = createMockComputer(1); JobOffer o = createMockOffer(c.getExecutors().get(0)); - MappingWorksheet mw = new MappingWorksheet(wrap(t), Collections.singletonList(o)); + MappingWorksheet mw = new MappingWorksheet(wrap(t), List.of(o)); // the test load predictor should have pushed down the executor count to 0 assertTrue(mw.executors.isEmpty()); diff --git a/test/src/test/java/hudson/security/ACLTest.java b/test/src/test/java/hudson/security/ACLTest.java index 7737ca19ebe7..07ea6e9c93e9 100644 --- a/test/src/test/java/hudson/security/ACLTest.java +++ b/test/src/test/java/hudson/security/ACLTest.java @@ -39,6 +39,7 @@ import hudson.model.User; import java.util.Collection; import java.util.Collections; +import java.util.List; import jenkins.model.Jenkins; import org.junit.Assert; import org.junit.Rule; @@ -65,7 +66,7 @@ public void bypassStrategyOnSystem() throws Exception { assertTrue(p.hasPermission2(ACL.SYSTEM2, Item.CONFIGURE)); p.checkPermission(Item.CONFIGURE); p.checkAbortPermission(); - assertEquals(Collections.singletonList(p), r.jenkins.getAllItems()); + assertEquals(List.of(p), r.jenkins.getAllItems()); } @Test diff --git a/test/src/test/java/hudson/security/TokenBasedRememberMeServices2Test.java b/test/src/test/java/hudson/security/TokenBasedRememberMeServices2Test.java index 7481fecbf71d..299f382c1d9c 100644 --- a/test/src/test/java/hudson/security/TokenBasedRememberMeServices2Test.java +++ b/test/src/test/java/hudson/security/TokenBasedRememberMeServices2Test.java @@ -17,7 +17,7 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; -import java.util.Collections; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import jenkins.model.Jenkins; @@ -84,7 +84,7 @@ private static class InvalidUserWhenLoggingBackInRealm extends AbstractPasswordB @Override protected UserDetails authenticate2(String username, String password) throws AuthenticationException { if (username.equals(password)) { - return new org.springframework.security.core.userdetails.User(username, password, Collections.singleton(new SimpleGrantedAuthority("myteam"))); + return new org.springframework.security.core.userdetails.User(username, password, Set.of(new SimpleGrantedAuthority("myteam"))); } throw new BadCredentialsException(username); } diff --git a/test/src/test/java/hudson/slaves/EnvironmentVariableNodePropertyTest.java b/test/src/test/java/hudson/slaves/EnvironmentVariableNodePropertyTest.java index 6acf60e2480b..6c7fa86ba44d 100644 --- a/test/src/test/java/hudson/slaves/EnvironmentVariableNodePropertyTest.java +++ b/test/src/test/java/hudson/slaves/EnvironmentVariableNodePropertyTest.java @@ -10,8 +10,8 @@ import hudson.model.ParametersDefinitionProperty; import hudson.model.StringParameterDefinition; import java.io.IOException; -import java.util.Collections; import java.util.Map; +import java.util.Set; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; @@ -54,7 +54,7 @@ public void testAgentPropertyOnAgent() throws Exception { @Test public void testControllerPropertyOnBuiltInNode() throws Exception { j.jenkins.getGlobalNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( + Set.of(new EnvironmentVariablesNodeProperty( new EnvironmentVariablesNodeProperty.Entry("KEY", "globalValue")))); Map envVars = executeBuild(j.jenkins); @@ -68,7 +68,7 @@ public void testControllerPropertyOnBuiltInNode() throws Exception { @Test public void testAgentAndControllerPropertyOnAgent() throws Exception { j.jenkins.getGlobalNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( + Set.of(new EnvironmentVariablesNodeProperty( new EnvironmentVariablesNodeProperty.Entry("KEY", "globalValue")))); setVariables(agent, new EnvironmentVariablesNodeProperty.Entry("KEY", "agentValue")); @@ -100,7 +100,7 @@ public void testAgentAndBuiltInNodePropertyAndParameterOnAgent() @Test public void testVariableResolving() throws Exception { j.jenkins.getGlobalNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( + Set.of(new EnvironmentVariablesNodeProperty( new EnvironmentVariablesNodeProperty.Entry("KEY1", "value"), new EnvironmentVariablesNodeProperty.Entry("KEY2", "$KEY1")))); Map envVars = executeBuild(j.jenkins); assertEquals("value", envVars.get("KEY1")); @@ -110,7 +110,7 @@ public void testVariableResolving() throws Exception { @Test public void testFormRoundTripForController() throws Exception { j.jenkins.getGlobalNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( + Set.of(new EnvironmentVariablesNodeProperty( new EnvironmentVariablesNodeProperty.Entry("KEY", "value")))); WebClient webClient = j.createWebClient(); @@ -153,7 +153,7 @@ public void setUp() throws Exception { private void setVariables(Node node, EnvironmentVariablesNodeProperty.Entry... entries) throws IOException { node.getNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( + Set.of(new EnvironmentVariablesNodeProperty( entries))); } diff --git a/test/src/test/java/hudson/slaves/NodeParallelTest.java b/test/src/test/java/hudson/slaves/NodeParallelTest.java index 0a75ec220c90..6e644268ffb7 100644 --- a/test/src/test/java/hudson/slaves/NodeParallelTest.java +++ b/test/src/test/java/hudson/slaves/NodeParallelTest.java @@ -39,7 +39,7 @@ public void createNodesWithParallelThreads() throws InterruptedException, Execut // r.createSlave(); DumbSlave agent = new DumbSlave("agent-" + i, "/tmp", new JNLPLauncher(true)); r.jenkins.addNode(agent); - agent.setNodeProperties(Collections.singletonList(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("foo", "" + i)))); + agent.setNodeProperties(List.of(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("foo", "" + i)))); return null; } catch (Exception e1) { throw new RuntimeException(e1); diff --git a/test/src/test/java/hudson/tasks/BuildTriggerTest.java b/test/src/test/java/hudson/tasks/BuildTriggerTest.java index 85a320f74c5c..5418d3d9e3ea 100644 --- a/test/src/test/java/hudson/tasks/BuildTriggerTest.java +++ b/test/src/test/java/hudson/tasks/BuildTriggerTest.java @@ -55,7 +55,6 @@ import hudson.security.ProjectMatrixAuthorizationStrategy; import hudson.util.FormValidation; import java.io.IOException; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -152,10 +151,10 @@ public void downstreamProjectSecurity() throws Exception { j.jenkins.setAuthorizationStrategy(auth); final FreeStyleProject upstream = j. createFreeStyleProject("upstream"); org.acegisecurity.Authentication alice = User.getOrCreateByIdOrFullName("alice").impersonate(); - QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap("upstream", alice))); + QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Map.of("upstream", alice))); Map> perms = new HashMap<>(); - perms.put(Item.READ, Collections.singleton("alice")); - perms.put(Item.CONFIGURE, Collections.singleton("alice")); + perms.put(Item.READ, Set.of("alice")); + perms.put(Item.CONFIGURE, Set.of("alice")); upstream.addProperty(new AuthorizationMatrixProperty(perms)); String downstreamName = "d0wnstr3am"; // do not clash with English messages! FreeStyleProject downstream = j.createFreeStyleProject(downstreamName); @@ -172,7 +171,7 @@ public void downstreamProjectSecurity() throws Exception { childProjects.setValueAttribute(downstreamName); submit(config); */ - assertEquals(Collections.singletonList(downstream), upstream.getDownstreamProjects()); + assertEquals(List.of(downstream), upstream.getDownstreamProjects()); // Downstream projects whose existence we are not aware of will silently not be triggered: assertDoCheck(alice, Messages.BuildTrigger_NoSuchProject(downstreamName, "upstream"), upstream, downstreamName); assertDoCheck(alice, null, null, downstreamName); @@ -182,7 +181,7 @@ public void downstreamProjectSecurity() throws Exception { assertNull(downstream.getLastBuild()); // If we can see them, but not build them, that is a warning (but this is in cleanUp so the build is still considered a success): Map> grantedPermissions = new HashMap<>(); - grantedPermissions.put(Item.READ, Collections.singleton("alice")); + grantedPermissions.put(Item.READ, Set.of("alice")); AuthorizationMatrixProperty amp = new AuthorizationMatrixProperty(grantedPermissions); downstream.addProperty(amp); assertDoCheck(alice, Messages.BuildTrigger_you_have_no_permission_to_build_(downstreamName), upstream, downstreamName); @@ -192,7 +191,7 @@ public void downstreamProjectSecurity() throws Exception { j.waitUntilNoActivity(); assertNull(downstream.getLastBuild()); // If we can build them, then great: - grantedPermissions.put(Item.BUILD, Collections.singleton("alice")); + grantedPermissions.put(Item.BUILD, Set.of("alice")); downstream.removeProperty(amp); amp = new AuthorizationMatrixProperty(grantedPermissions); downstream.addProperty(amp); @@ -207,7 +206,7 @@ public void downstreamProjectSecurity() throws Exception { assertNotNull(cause); assertEquals(b, cause.getUpstreamRun()); // Now if we have configured some QIA’s but they are not active on this job, we should normally fall back to running as anonymous. Which would normally have no permissions: - QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(Collections.singletonMap("upstream", Jenkins.ANONYMOUS))); + QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(Map.of("upstream", Jenkins.ANONYMOUS))); assertDoCheck(alice, Messages.BuildTrigger_you_have_no_permission_to_build_(downstreamName), upstream, downstreamName); assertDoCheck(alice, null, null, downstreamName); b = j.buildAndAssertSuccess(upstream); @@ -215,8 +214,8 @@ public void downstreamProjectSecurity() throws Exception { j.waitUntilNoActivity(); assertEquals(1, downstream.getLastBuild().number); // Unless we explicitly granted them: - grantedPermissions.put(Item.READ, Collections.singleton("anonymous")); - grantedPermissions.put(Item.BUILD, Collections.singleton("anonymous")); + grantedPermissions.put(Item.READ, Set.of("anonymous")); + grantedPermissions.put(Item.BUILD, Set.of("anonymous")); downstream.removeProperty(amp); amp = new AuthorizationMatrixProperty(grantedPermissions); downstream.addProperty(amp); diff --git a/test/src/test/java/hudson/tasks/FingerprinterTest.java b/test/src/test/java/hudson/tasks/FingerprinterTest.java index 4e99be1af063..fc58b79127d8 100644 --- a/test/src/test/java/hudson/tasks/FingerprinterTest.java +++ b/test/src/test/java/hudson/tasks/FingerprinterTest.java @@ -53,9 +53,9 @@ import java.io.File; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; import jenkins.model.Jenkins; import org.junit.BeforeClass; import org.junit.Rule; @@ -122,7 +122,7 @@ public static void setUp() { private static class FingerprintAddingBuilder extends Builder { @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { - build.addAction(new Fingerprinter.FingerprintAction(build, Collections.singletonMap(singleFiles2[0], "fakefingerprint"))); + build.addAction(new Fingerprinter.FingerprintAction(build, Map.of(singleFiles2[0], "fakefingerprint"))); return true; } } @@ -349,8 +349,8 @@ public void fingerprintCleanup() throws Exception { j.jenkins.rebuildDependencyGraph(); - assertEquals(Collections.singletonList(p1), p2.getUpstreamProjects()); - assertEquals(Collections.singletonList(p1), p3.getUpstreamProjects()); + assertEquals(List.of(p1), p2.getUpstreamProjects()); + assertEquals(List.of(p1), p3.getUpstreamProjects()); assertEquals(new HashSet(Arrays.asList(p2, p3)), new HashSet(p1.getDownstreamProjects())); // discard the p3 records @@ -361,8 +361,8 @@ public void fingerprintCleanup() throws Exception { // records for p3 should have been deleted now assertEquals(2, f.getUsages().size()); - assertEquals(Collections.singletonList(p1), p2.getUpstreamProjects()); - assertEquals(Collections.singletonList(p2), p1.getDownstreamProjects()); + assertEquals(List.of(p1), p2.getUpstreamProjects()); + assertEquals(List.of(p2), p1.getDownstreamProjects()); // do a new build in p2 #2 that points to a separate fingerprints diff --git a/test/src/test/java/hudson/tasks/LogRotatorTest.java b/test/src/test/java/hudson/tasks/LogRotatorTest.java index da5da0f15211..a7c6c9154e90 100644 --- a/test/src/test/java/hudson/tasks/LogRotatorTest.java +++ b/test/src/test/java/hudson/tasks/LogRotatorTest.java @@ -45,6 +45,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.Collections; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; @@ -69,7 +70,7 @@ public void successVsFailure() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setLogRotator(new LogRotator(-1, 2, -1, -1)); j.buildAndAssertSuccess(project); // #1 - project.getBuildersList().replaceBy(Collections.singleton(new FailureBuilder())); + project.getBuildersList().replaceBy(Set.of(new FailureBuilder())); j.buildAndAssertStatus(Result.FAILURE, project); // #2 j.buildAndAssertStatus(Result.FAILURE, project); // #3 assertEquals(1, numberOf(project.getLastSuccessfulBuild())); @@ -87,7 +88,7 @@ public void stableVsUnstable() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setLogRotator(new LogRotator(-1, 2, -1, -1)); j.buildAndAssertSuccess(project); // #1 - project.getPublishersList().replaceBy(Collections.singleton(new TestsFail())); + project.getPublishersList().replaceBy(Set.of(new TestsFail())); j.buildAndAssertStatus(Result.UNSTABLE, project); // #2 j.buildAndAssertStatus(Result.UNSTABLE, project); // #3 assertEquals(1, numberOf(project.getLastStableBuild())); @@ -102,10 +103,10 @@ public void stableVsUnstable() throws Exception { public void artifactDelete() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setLogRotator(new LogRotator(-1, 6, -1, 2)); - project.getPublishersList().replaceBy(Collections.singleton(new ArtifactArchiver("f", "", true, false))); + project.getPublishersList().replaceBy(Set.of(new ArtifactArchiver("f", "", true, false))); j.buildAndAssertStatus(Result.FAILURE, project); // #1 assertFalse(project.getBuildByNumber(1).getHasArtifacts()); - project.getBuildersList().replaceBy(Collections.singleton(new CreateArtifact())); + project.getBuildersList().replaceBy(Set.of(new CreateArtifact())); j.buildAndAssertSuccess(project); // #2 assertTrue(project.getBuildByNumber(2).getHasArtifacts()); project.getBuildersList().replaceBy(Arrays.asList(new CreateArtifact(), new FailureBuilder())); @@ -121,7 +122,7 @@ public void artifactDelete() throws Exception { assertFalse("no better than #4", project.getBuildByNumber(3).getHasArtifacts()); assertTrue(project.getBuildByNumber(4).getHasArtifacts()); assertTrue(project.getBuildByNumber(5).getHasArtifacts()); - project.getBuildersList().replaceBy(Collections.singleton(new CreateArtifact())); + project.getBuildersList().replaceBy(Set.of(new CreateArtifact())); j.buildAndAssertSuccess(project); // #6 assertFalse("#2 is still lastSuccessful until #6 is complete", project.getBuildByNumber(2).getHasArtifacts()); assertFalse(project.getBuildByNumber(3).getHasArtifacts()); diff --git a/test/src/test/java/hudson/tasks/MavenTest.java b/test/src/test/java/hudson/tasks/MavenTest.java index 700372cfb6c3..1d627427acb9 100644 --- a/test/src/test/java/hudson/tasks/MavenTest.java +++ b/test/src/test/java/hudson/tasks/MavenTest.java @@ -52,6 +52,7 @@ import hudson.tools.ToolPropertyDescriptor; import hudson.util.DescribableList; import java.util.Collections; +import java.util.Set; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import jenkins.mvn.DefaultGlobalSettingsProvider; @@ -114,7 +115,7 @@ public class MavenTest { JDK varJDK = new JDK("varJDK", javaHomeVar); j.jenkins.getJDKs().add(varJDK); j.jenkins.getNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( + Set.of(new EnvironmentVariablesNodeProperty( new EnvironmentVariablesNodeProperty.Entry("VAR_MAVEN", mavenVar), new EnvironmentVariablesNodeProperty.Entry("VAR_JAVA", javaVar)))); @@ -215,7 +216,7 @@ public void parametersReferencedFromPropertiesShouldRetainBackslashes() throws E project.getBuildersList().add(new Maven("--help", null, null, properties, null, false, null, null, true)); project.addProperty(new ParametersDefinitionProperty(parameter)); - j.jenkins.getNodeProperties().replaceBy(Collections.singleton( + j.jenkins.getNodeProperties().replaceBy(Set.of( new EnvironmentVariablesNodeProperty(envVar) )); diff --git a/test/src/test/java/hudson/tools/InstallerTranslatorTest.java b/test/src/test/java/hudson/tools/InstallerTranslatorTest.java index b5f053666cd9..2e9fac2e6164 100644 --- a/test/src/test/java/hudson/tools/InstallerTranslatorTest.java +++ b/test/src/test/java/hudson/tools/InstallerTranslatorTest.java @@ -40,6 +40,7 @@ import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; +import java.util.List; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -53,7 +54,7 @@ public class InstallerTranslatorTest { @Test public void offlineNodeForJDK() throws Exception { Node slave = new DumbSlave("disconnected-slave", null, "/wherever", "1", Node.Mode.NORMAL, null, new JNLPLauncher(true), RetentionStrategy.NOOP, Collections.emptyList()); String globalDefaultLocation = "/usr/lib/jdk"; - JDK jdk = new JDK("my-jdk", globalDefaultLocation, Collections.singletonList(new InstallSourceProperty(Collections.singletonList(new CommandInstaller(null, "irrelevant", "/opt/jdk"))))); + JDK jdk = new JDK("my-jdk", globalDefaultLocation, List.of(new InstallSourceProperty(List.of(new CommandInstaller(null, "irrelevant", "/opt/jdk"))))); r.jenkins.getJDKs().add(jdk); FreeStyleProject p = r.createFreeStyleProject(); p.setJDK(jdk); @@ -72,14 +73,14 @@ public class InstallerTranslatorTest { JDK jdk1 = new JDK( "jdk1", null, - Collections.singletonList(new InstallSourceProperty(Collections.singletonList( + List.of(new InstallSourceProperty(List.of( Functions.isWindows() ? new BatchCommandInstaller(null, "echo installed jdk1", jdk1Path) : new CommandInstaller(null, "echo installed jdk1", jdk1Path))))); JDK jdk2 = new JDK( "jdk2", null, - Collections.singletonList(new InstallSourceProperty(Collections.singletonList( + List.of(new InstallSourceProperty(List.of( Functions.isWindows() ? new BatchCommandInstaller(null, "echo installed jdk2", jdk2Path) : new CommandInstaller(null, "echo installed jdk2", jdk2Path))))); @@ -120,7 +121,7 @@ public void testMessageLoggedWhenNoInstallerFound() throws Exception { final BatchCommandInstaller bci = new BatchCommandInstaller("wrong2", "echo hello", "/opt/jdk2"); InstallSourceProperty isp = new InstallSourceProperty(Arrays.asList(ci, bci)); - JDK jdk = new JDK("jdk", null, Collections.singletonList(isp)); + JDK jdk = new JDK("jdk", null, List.of(isp)); r.jenkins.getJDKs().add(jdk); @@ -143,7 +144,7 @@ public void testNoMessageLoggedWhenAnyInstallerFound() throws Exception { : new CommandInstaller("built-in", "echo hello", "/opt/jdk2"); InstallSourceProperty isp = new InstallSourceProperty(Arrays.asList(ci, ci2)); - JDK jdk = new JDK("jdk", null, Collections.singletonList(isp)); + JDK jdk = new JDK("jdk", null, List.of(isp)); r.jenkins.getJDKs().add(jdk); diff --git a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java index 8d16c789b8a3..5eb3cecd5500 100644 --- a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java +++ b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java @@ -47,7 +47,6 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import jenkins.model.Jenkins; import net.sourceforge.htmlunit.corejs.javascript.Function; @@ -84,7 +83,7 @@ public void onlyAdminCanReachTheDoCheck() throws Exception { User.getById(USER, true); WebRequest request = new WebRequest(new URL(j.getURL() + "descriptorByName/hudson.tools.ZipExtractionInstaller/checkUrl"), HttpMethod.POST); - request.setRequestBody(URLEncoder.encode("value=https://www.google.com", StandardCharsets.UTF_8.name())); + request.setRequestBody(URLEncoder.encode("value=https://www.google.com", StandardCharsets.UTF_8)); JenkinsRule.WebClient adminWc = j.createWebClient(); adminWc.login(ADMIN); @@ -104,8 +103,8 @@ public void roundtrip() throws Exception { ZipExtractionInstaller installer = new ZipExtractionInstaller("", VALID_URL, ""); - j.jenkins.getJDKs().add(new JDK("test", tmp.getRoot().getAbsolutePath(), Collections.singletonList( - new InstallSourceProperty(Collections.singletonList(installer))))); + j.jenkins.getJDKs().add(new JDK("test", tmp.getRoot().getAbsolutePath(), List.of( + new InstallSourceProperty(List.of(installer))))); JenkinsRule.WebClient wc = j.createWebClient(); @@ -115,7 +114,7 @@ public void roundtrip() throws Exception { HtmlPage page = wc.goTo("configureTools"); XMLHttpRequest lastRequest = jsEngine.getLastRequest(); - String body = URLDecoder.decode(getPrivateWebRequestField(lastRequest).getRequestBody(), "UTF-8"); + String body = URLDecoder.decode(getPrivateWebRequestField(lastRequest).getRequestBody(), StandardCharsets.UTF_8); assertThat(body, containsString(VALID_URL)); assertEquals(FormValidation.ok().renderHtml(), lastRequest.getResponseText()); @@ -131,7 +130,7 @@ public void roundtrip() throws Exception { wc.goTo("configureTools"); lastRequest = jsEngine.getLastRequest(); - body = URLDecoder.decode(getPrivateWebRequestField(lastRequest).getRequestBody(), "UTF-8"); + body = URLDecoder.decode(getPrivateWebRequestField(lastRequest).getRequestBody(), StandardCharsets.UTF_8); assertThat(body, containsString(INVALID_URL)); assertThat(lastRequest.getResponseText(), containsString(Messages.ZipExtractionInstaller_malformed_url())); } diff --git a/test/src/test/java/hudson/util/ArgumentListBuilder2Test.java b/test/src/test/java/hudson/util/ArgumentListBuilder2Test.java index 897fa0947c88..52d2e59ada5e 100644 --- a/test/src/test/java/hudson/util/ArgumentListBuilder2Test.java +++ b/test/src/test/java/hudson/util/ArgumentListBuilder2Test.java @@ -148,6 +148,6 @@ public String echoArgs(String... arguments) throws Exception { listener.close(); assumeThat("Failed to run " + args, code, equalTo(0)); - return out.toString(Charset.defaultCharset().name()); + return out.toString(Charset.defaultCharset()); } } diff --git a/test/src/test/java/hudson/util/BootFailureTest.java b/test/src/test/java/hudson/util/BootFailureTest.java index adbe0b06081c..6bfe5f824359 100644 --- a/test/src/test/java/hudson/util/BootFailureTest.java +++ b/test/src/test/java/hudson/util/BootFailureTest.java @@ -13,7 +13,6 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; @@ -162,7 +161,7 @@ public void interruptedStartup() throws Exception { d.mkdirs(); FileUtils.write(new File(d, "1.groovy"), "hudson.util.BootFailureTest.runRecord << '1'", StandardCharsets.UTF_8); j.newHudson(); - assertEquals(Collections.singletonList("1"), runRecord); + assertEquals(List.of("1"), runRecord); } @TestExtension("interruptedStartup") diff --git a/test/src/test/java/hudson/util/ProcessTreeTest.java b/test/src/test/java/hudson/util/ProcessTreeTest.java index 7e0a6e668bb9..ddf928f5f4ac 100644 --- a/test/src/test/java/hudson/util/ProcessTreeTest.java +++ b/test/src/test/java/hudson/util/ProcessTreeTest.java @@ -21,7 +21,7 @@ import java.io.File; import java.io.IOException; import java.io.StringWriter; -import java.util.Collections; +import java.util.Map; import org.junit.After; import org.junit.Assume; import org.junit.Rule; @@ -142,7 +142,7 @@ public void considersKillingVetos() throws Exception { process = pb.start(); ProcessTree processTree = ProcessTree.get(); - processTree.killAll(Collections.singletonMap("cookie", "testKeepDaemonsAlive")); + processTree.killAll(Map.of("cookie", "testKeepDaemonsAlive")); assertThrows("Process should have been excluded from the killing", IllegalThreadStateException.class, () -> process.exitValue()); } @@ -172,7 +172,7 @@ public void considersKillingVetosOnSlave() throws Exception { // Call killall (somewhat roundabout though) to (not) kill it StringWriter out = new StringWriter(); - s.createLauncher(new StreamTaskListener(out)).kill(Collections.singletonMap("cookie", "testKeepDaemonsAlive")); + s.createLauncher(new StreamTaskListener(out)).kill(Map.of("cookie", "testKeepDaemonsAlive")); assertThrows("Process should have been excluded from the killing", IllegalThreadStateException.class, () -> process.exitValue()); } diff --git a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java index 529e00f32850..b4c36aaae8e7 100644 --- a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java +++ b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java @@ -49,8 +49,8 @@ import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; -import java.util.Collections; import java.util.Map; +import java.util.Set; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.junit.Rule; @@ -75,7 +75,7 @@ public class RobustReflectionConverterTest { assertTrue("There should be no triggers", p.getTriggers().isEmpty()); OldDataMonitor odm = (OldDataMonitor) r.jenkins.getAdministrativeMonitor("OldData"); Map data = odm.getData(); - assertEquals(Collections.singleton(p), data.keySet()); + assertEquals(Set.of(p), data.keySet()); String text = data.values().iterator().next().extra; assertTrue(text, text.contains("hudson.triggers.TimerTrigger.readResolve")); } diff --git a/test/src/test/java/jenkins/cli/StopBuildsCommandTest.java b/test/src/test/java/jenkins/cli/StopBuildsCommandTest.java index 77c139038aa8..e86ad4235e03 100644 --- a/test/src/test/java/jenkins/cli/StopBuildsCommandTest.java +++ b/test/src/test/java/jenkins/cli/StopBuildsCommandTest.java @@ -35,7 +35,6 @@ import hudson.model.Item; import hudson.model.Result; import java.io.IOException; -import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import jenkins.model.Jenkins; @@ -59,7 +58,7 @@ public void shouldStopLastBuild() throws Exception { final FreeStyleProject project = createLongRunningProject(TEST_JOB_NAME); FreeStyleBuild build = project.scheduleBuild2(0).waitForStart(); j.waitForMessage("Sleeping", build); - final String stdout = runWith(Collections.singletonList(TEST_JOB_NAME)).stdout(); + final String stdout = runWith(List.of(TEST_JOB_NAME)).stdout(); assertThat(stdout, equalTo("Build '#1' stopped for job 'jobName'" + LN)); @@ -72,7 +71,7 @@ public void shouldNotStopEndedBuild() throws Exception { project.getBuildersList().add(new SleepBuilder(TimeUnit.SECONDS.toMillis(1))); j.buildAndAssertSuccess(project); - final String out = runWith(Collections.singletonList(TEST_JOB_NAME)).stdout(); + final String out = runWith(List.of(TEST_JOB_NAME)).stdout(); assertThat(out, equalTo("No builds stopped" + LN)); } @@ -87,7 +86,7 @@ public void shouldStopSeveralWorkingBuilds() throws Exception { FreeStyleBuild b2 = project.scheduleBuild2(0).waitForStart(); j.waitForMessage("Sleeping", b2); - final String stdout = runWith(Collections.singletonList(TEST_JOB_NAME)).stdout(); + final String stdout = runWith(List.of(TEST_JOB_NAME)).stdout(); assertThat(stdout, equalTo("Build '#2' stopped for job 'jobName'" + LN + "Build '#1' stopped for job 'jobName'" + LN)); @@ -100,14 +99,14 @@ public void shouldReportNotSupportedType() throws Exception { final String testFolderName = "folder"; j.createFolder(testFolderName); - final String stderr = runWith(Collections.singletonList(testFolderName)).stderr(); + final String stderr = runWith(List.of(testFolderName)).stderr(); assertThat(stderr, equalTo(LN + "ERROR: Job not found: 'folder'" + LN)); } @Test public void shouldDoNothingIfJobNotFound() throws Exception { - final String stderr = runWith(Collections.singletonList(TEST_JOB_NAME)).stderr(); + final String stderr = runWith(List.of(TEST_JOB_NAME)).stderr(); assertThat(stderr, equalTo(LN + "ERROR: Job not found: 'jobName'" + LN)); } @@ -136,7 +135,7 @@ public void shouldReportBuildStopError() throws Exception { FreeStyleBuild build = project.scheduleBuild2(0).waitForStart(); j.waitForMessage("Sleeping", build); - final String stdout = runWith(Collections.singletonList(TEST_JOB_NAME)).stdout(); + final String stdout = runWith(List.of(TEST_JOB_NAME)).stdout(); assertThat(stdout, equalTo("Exception occurred while trying to stop build '#1' for job 'jobName'. " + diff --git a/test/src/test/java/jenkins/install/SetupWizardTest.java b/test/src/test/java/jenkins/install/SetupWizardTest.java index 23664e0961c0..a966e59d1c3d 100644 --- a/test/src/test/java/jenkins/install/SetupWizardTest.java +++ b/test/src/test/java/jenkins/install/SetupWizardTest.java @@ -90,7 +90,7 @@ public void initSetupWizard() throws IOException, InterruptedException { final FilePath adminPassFile = wizard.getInitialAdminPasswordFile(); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); adminPassFile.copyTo(ostream); - final String password = ostream.toString(StandardCharsets.UTF_8.name()); + final String password = ostream.toString(StandardCharsets.UTF_8); } @Test diff --git a/test/src/test/java/jenkins/model/TransientActionFactoryTest.java b/test/src/test/java/jenkins/model/TransientActionFactoryTest.java index c1750b4fd902..62208fcf0397 100644 --- a/test/src/test/java/jenkins/model/TransientActionFactoryTest.java +++ b/test/src/test/java/jenkins/model/TransientActionFactoryTest.java @@ -46,8 +46,8 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collection; -import java.util.Collections; import java.util.List; +import java.util.Set; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; @@ -75,7 +75,7 @@ public class TransientActionFactoryTest { } @Override public Collection createFor(AbstractItem i) { - return Collections.singleton(new MyAction()); + return Set.of(new MyAction()); } } @@ -144,7 +144,7 @@ private static class MyAction implements Action { @Override public Collection createFor(AbstractProject p) { count++; - return Collections.singleton(new MyProminentProjectAction()); + return Set.of(new MyProminentProjectAction()); } } @@ -178,7 +178,7 @@ private static class MyAction implements Action { @Override public Collection createFor(FreeStyleProject p) { count++; - return Collections.singleton(new MyProminentProjectAction()); + return Set.of(new MyProminentProjectAction()); } } @@ -203,7 +203,7 @@ public Class type() { @NonNull @Override public Collection createFor(@NonNull Actionable target) { - return Collections.singleton(new MyProminentProjectAction()); + return Set.of(new MyProminentProjectAction()); } } diff --git a/test/src/test/java/jenkins/security/ClassFilterImplTest.java b/test/src/test/java/jenkins/security/ClassFilterImplTest.java index 123a8c3b4fe8..b578980d1428 100644 --- a/test/src/test/java/jenkins/security/ClassFilterImplTest.java +++ b/test/src/test/java/jenkins/security/ClassFilterImplTest.java @@ -49,8 +49,8 @@ import hudson.tasks.Builder; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.Map; +import java.util.Set; import java.util.logging.Level; import jenkins.model.GlobalConfiguration; import org.apache.commons.io.FileUtils; @@ -160,7 +160,7 @@ public void xstreamRequiresWhitelist() throws Exception { assertNull(config.obj); assertEquals("modified", config.unrelated); Map data = ExtensionList.lookupSingleton(OldDataMonitor.class).getData(); - assertEquals(Collections.singleton(config), data.keySet()); + assertEquals(Set.of(config), data.keySet()); assertThat(data.values().iterator().next().extra, allOf(containsString("LinkedListMultimap"), containsString("https://www.jenkins.io/redirect/class-filter/"))); } diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java index 3a9ab885fcb3..6ad3868d5752 100644 --- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java +++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java @@ -45,7 +45,7 @@ import hudson.model.User; import java.io.File; import java.net.URL; -import java.util.Collections; +import java.util.List; import java.util.concurrent.atomic.AtomicReference; import jenkins.security.ApiTokenProperty; import net.sf.json.JSONObject; @@ -86,7 +86,7 @@ public void roundtripWithRestart() throws Throwable { wc.getOptions().setThrowExceptionOnFailingStatusCode(false); WebRequest request = new WebRequest(new URL(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); - request.setRequestParameters(Collections.singletonList(new NameValuePair("newTokenName", TOKEN_NAME))); + request.setRequestParameters(List.of(new NameValuePair("newTokenName", TOKEN_NAME))); Page page = wc.getPage(request); assertEquals(200, page.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java index d81c94b02a66..e6798fe44f41 100644 --- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java +++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java @@ -43,7 +43,7 @@ import com.gargoylesoftware.htmlunit.xml.XmlPage; import hudson.model.User; import java.net.URL; -import java.util.Collections; +import java.util.List; import jenkins.security.ApiTokenProperty; import net.sf.json.JSONObject; import org.junit.Rule; @@ -74,7 +74,7 @@ public void roundtrip() throws Exception { final String TOKEN_NAME = "New Token Name"; WebRequest request = new WebRequest(new URL(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); - request.setRequestParameters(Collections.singletonList(new NameValuePair("newTokenName", TOKEN_NAME))); + request.setRequestParameters(List.of(new NameValuePair("newTokenName", TOKEN_NAME))); Page page = wc.getPage(request); assertEquals(200, page.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java b/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java index d610eab93bdf..ecdf16910d77 100644 --- a/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java +++ b/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java @@ -14,6 +14,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Enumeration; +import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.ServletRequest; @@ -172,7 +173,7 @@ public static class TestNewRulesOk extends AbstractUnprotectedRootAction { @JsonResponse // does not support list public Map doAnnotatedJsonResponse() { - return Collections.singletonMap("a", "b"); + return Map.of("a", "b"); } @LimitedTo("admin") @@ -391,7 +392,7 @@ public void testAnnotatedParameterOk_annotatedParamJsonBody() throws Exception { // WebClient forces us to use POST to have the possibility to send requestBody settings.setHttpMethod(HttpMethod.POST); settings.setAdditionalHeader("Content-Type", "application/json"); - settings.setRequestBody(JSONObject.fromObject(Collections.singletonMap("name", "Test")).toString()); + settings.setRequestBody(JSONObject.fromObject(Map.of("name", "Test")).toString()); assertReachableWithSettings(settings); } @@ -400,10 +401,10 @@ public void testAnnotatedParameterOk_annotatedParamSubmittedForm() throws Except WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedParamSubmittedForm/")); settings.setHttpMethod(HttpMethod.POST); - settings.setRequestParameters(Collections.singletonList( + settings.setRequestParameters(List.of( new NameValuePair( "json", - JSONObject.fromObject(Collections.singletonMap("name", "Test")).toString() + JSONObject.fromObject(Map.of("name", "Test")).toString() ) )); assertReachableWithSettings(settings); diff --git a/test/src/test/java/jenkins/security/stapler/GetterMethodFilterTest.java b/test/src/test/java/jenkins/security/stapler/GetterMethodFilterTest.java index cadffd3512b0..e5e227d74eb0 100644 --- a/test/src/test/java/jenkins/security/stapler/GetterMethodFilterTest.java +++ b/test/src/test/java/jenkins/security/stapler/GetterMethodFilterTest.java @@ -144,11 +144,11 @@ public List getList() { // as we cannot determine the element class due to type erasure, this is reachable public List getListOfPoint() { - return Collections.singletonList(new RenderablePoint()); + return List.of(new RenderablePoint()); } public List> getListOfList() { - return Collections.singletonList(Arrays.asList(new Renderable(), new Renderable())); + return List.of(Arrays.asList(new Renderable(), new Renderable())); } public Renderable[] getArray() { @@ -176,7 +176,7 @@ public Renderable[][] getArrayOfArray() { @SuppressWarnings("unchecked") public List[] getArrayOfList() { List list = Arrays.asList(new Renderable(), new Renderable()); - return (List[]) Collections.singletonList(list).toArray(new List[0]); + return (List[]) List.of(list).toArray(new List[0]); } public List getListOfArray() { @@ -186,7 +186,7 @@ public List getListOfArray() { } public Map getMap() { - return Collections.singletonMap("a", new Renderable()); + return Map.of("a", new Renderable()); } } diff --git a/test/src/test/java/jenkins/security/stapler/Security400Test.java b/test/src/test/java/jenkins/security/stapler/Security400Test.java index 1e6584be2837..60612e9a5b84 100644 --- a/test/src/test/java/jenkins/security/stapler/Security400Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security400Test.java @@ -53,6 +53,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -338,7 +339,7 @@ public void ensureDoStopBuildWorks() throws Exception { QueueTaskFuture futureBuild = p.scheduleBuild2(0); FreeStyleBuild build = futureBuild.waitForStart(); - String runExtId = URLEncoder.encode(build.getExternalizableId(), "UTF-8"); + String runExtId = URLEncoder.encode(build.getExternalizableId(), StandardCharsets.UTF_8); WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=" + runExtId), HttpMethod.POST); Page page = wc.getPage(request); diff --git a/test/src/test/java/jenkins/tasks/filters/impl/RetainVariablesLocalRuleTest.java b/test/src/test/java/jenkins/tasks/filters/impl/RetainVariablesLocalRuleTest.java index 1cd838bb20e3..a15afe1b77d7 100644 --- a/test/src/test/java/jenkins/tasks/filters/impl/RetainVariablesLocalRuleTest.java +++ b/test/src/test/java/jenkins/tasks/filters/impl/RetainVariablesLocalRuleTest.java @@ -43,7 +43,6 @@ import hudson.tasks.BatchFile; import hudson.tasks.Shell; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.junit.Rule; @@ -70,7 +69,7 @@ public void retainVariable_removeUnwantedVariables_batch() throws Exception { { // the rule allows the user to retain only a subset of variable RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -84,7 +83,7 @@ public void retainVariable_removeUnwantedVariables_batch() throws Exception { { // the rule allows the user to retain only a subset of variable (second example) RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("who"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -114,7 +113,7 @@ public void retainVariable_removeModifiedSystemEnv_batch() throws Exception { { // no attempt to modify path (except other plugin) RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello") @@ -127,7 +126,7 @@ public void retainVariable_removeModifiedSystemEnv_batch() throws Exception { { // does not accept modification of path RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -143,7 +142,7 @@ public void retainVariable_removeModifiedSystemEnv_batch() throws Exception { { // accept modification of path RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what path"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -174,7 +173,7 @@ public void retainVariable_removeModifiedSystemEnv_shell() throws Exception { { // no attempt to modify path (except other plugin) RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello") @@ -187,7 +186,7 @@ public void retainVariable_removeModifiedSystemEnv_shell() throws Exception { { // does not accept modification of path RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -203,7 +202,7 @@ public void retainVariable_removeModifiedSystemEnv_shell() throws Exception { { // accept modification of path RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what path"); - batch.setConfiguredLocalRules(Collections.singletonList(localRule)); + batch.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -231,7 +230,7 @@ public void retainVariable_removeUnwantedVariables_shell() throws Exception { { // the rule allows the user to retain only a subset of variable RetainVariablesLocalRule localRule = new RetainVariablesLocalRule(); localRule.setVariables("what"); - shell.setConfiguredLocalRules(Collections.singletonList(localRule)); + shell.setConfiguredLocalRules(List.of(localRule)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -262,7 +261,7 @@ public void retainVariable_removeSystemVariables_shell() throws Exception { localRule.setVariables("path"); // seems to work without but may be env dependent localRule.setRetainCharacteristicEnvVars(false); localRule.setProcessVariablesHandling(RetainVariablesLocalRule.ProcessVariablesHandling.REMOVE); - filteredShell.setConfiguredLocalRules(Collections.singletonList(localRule)); + filteredShell.setConfiguredLocalRules(List.of(localRule)); p.getBuildersList().add(filteredShell); build = j.buildAndAssertSuccess(p); @@ -295,12 +294,12 @@ public void multipleBuildSteps_haveSeparateRules_batch() throws Exception { RetainVariablesLocalRule localRule1 = new RetainVariablesLocalRule(); // take care to allow the PATH to be used, without that the cmd is not found localRule1.setVariables("what"); - batch1.setConfiguredLocalRules(Collections.singletonList(localRule1)); + batch1.setConfiguredLocalRules(List.of(localRule1)); RetainVariablesLocalRule localRule2 = new RetainVariablesLocalRule(); // take care to allow the PATH to be used, without that the cmd is not found localRule2.setVariables("who"); - batch2.setConfiguredLocalRules(Collections.singletonList(localRule2)); + batch2.setConfiguredLocalRules(List.of(localRule2)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), @@ -332,12 +331,12 @@ public void multipleBuildSteps_haveSeparateRules_shell() throws Exception { RetainVariablesLocalRule localRule1 = new RetainVariablesLocalRule(); // take care to allow the PATH to be used, without that the cmd is not found localRule1.setVariables("what"); - batch1.setConfiguredLocalRules(Collections.singletonList(localRule1)); + batch1.setConfiguredLocalRules(List.of(localRule1)); RetainVariablesLocalRule localRule2 = new RetainVariablesLocalRule(); // take care to allow the PATH to be used, without that the cmd is not found localRule2.setVariables("who"); - batch2.setConfiguredLocalRules(Collections.singletonList(localRule2)); + batch2.setConfiguredLocalRules(List.of(localRule2)); FreeStyleBuild build = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0, (Cause) null, new ParametersAction( new StringParameterValue("what", "hello"), diff --git a/test/src/test/java/jenkins/triggers/ReverseBuildTriggerTest.java b/test/src/test/java/jenkins/triggers/ReverseBuildTriggerTest.java index 1cbfada7afaa..abdde448e8ce 100644 --- a/test/src/test/java/jenkins/triggers/ReverseBuildTriggerTest.java +++ b/test/src/test/java/jenkins/triggers/ReverseBuildTriggerTest.java @@ -42,9 +42,10 @@ import hudson.tasks.BuildTrigger; import hudson.tasks.BuildTriggerTest; import hudson.triggers.Trigger; -import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Set; import jenkins.model.Jenkins; import jenkins.security.QueueItemAuthenticatorConfiguration; import org.junit.Before; @@ -74,7 +75,7 @@ public void runMoreQuickly() throws Exception { FreeStyleProject downstream = r.createFreeStyleProject("downstream"); FreeStyleProject wayDownstream = r.createFreeStyleProject("wayDownstream"); downstream.addTrigger(new ReverseBuildTrigger("upstream", Result.SUCCESS)); - downstream.getPublishersList().add(new BuildTrigger(Collections.singleton(wayDownstream), Result.SUCCESS)); + downstream.getPublishersList().add(new BuildTrigger(Set.of(wayDownstream), Result.SUCCESS)); downstream.save(); r.configRoundtrip(downstream); ReverseBuildTrigger rbt = downstream.getTrigger(ReverseBuildTrigger.class); @@ -83,7 +84,7 @@ public void runMoreQuickly() throws Exception { assertEquals(Result.SUCCESS, rbt.getThreshold()); BuildTrigger bt = downstream.getPublishersList().get(BuildTrigger.class); assertNotNull(bt); - assertEquals(Collections.singletonList(wayDownstream), bt.getChildProjects(downstream)); + assertEquals(List.of(wayDownstream), bt.getChildProjects(downstream)); assertEquals(Result.SUCCESS, bt.getThreshold()); } @@ -105,7 +106,7 @@ public void runMoreQuickly() throws Exception { downstream.addTrigger(t); t.start(downstream, true); // as in AbstractProject.submit r.jenkins.rebuildDependencyGraph(); // as in AbstractProject.doConfigSubmit - assertEquals(Collections.singletonList(downstream), upstream.getDownstreamProjects()); + assertEquals(List.of(downstream), upstream.getDownstreamProjects()); // TODO could check doCheckUpstreamProjects, though it is not terribly interesting // Legacy mode: alice has no read permission on upstream but it works anyway FreeStyleBuild b = r.buildAndAssertSuccess(upstream); diff --git a/test/src/test/java/lib/form/HeteroListTest.java b/test/src/test/java/lib/form/HeteroListTest.java index c2c5b93b9f50..565421f14a8e 100644 --- a/test/src/test/java/lib/form/HeteroListTest.java +++ b/test/src/test/java/lib/form/HeteroListTest.java @@ -70,7 +70,7 @@ public void xssPrevented_heteroList_usingDescriptorDisplayName() throws Exceptio RootActionImpl rootAction = ExtensionList.lookupSingleton(RootActionImpl.class); TestItemDescribable.DynamicDisplayNameDescriptor dynamic = ExtensionList.lookupSingleton(TestItemDescribable.DynamicDisplayNameDescriptor.class); - rootAction.descriptorList = Collections.singletonList(dynamic); + rootAction.descriptorList = List.of(dynamic); dynamic.displayName = "DisplayName"; diff --git a/test/src/test/java/lib/form/PasswordTest.java b/test/src/test/java/lib/form/PasswordTest.java index 0c16e47b4b1d..b1fb2338e0ce 100644 --- a/test/src/test/java/lib/form/PasswordTest.java +++ b/test/src/test/java/lib/form/PasswordTest.java @@ -67,7 +67,7 @@ import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import jenkins.model.GlobalConfiguration; @@ -176,8 +176,8 @@ public void testExposedCiphertext() throws Exception { getJobCommand.setTransportAuth2(adminAuth); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String pName = p.getFullName(); - getJobCommand.main(Collections.singletonList(pName), Locale.ENGLISH, System.in, new PrintStream(baos), System.err); - assertEquals(xmlAdmin, baos.toString(configXml.getWebResponse().getContentCharset().name())); + getJobCommand.main(List.of(pName), Locale.ENGLISH, System.in, new PrintStream(baos), System.err); + assertEquals(xmlAdmin, baos.toString(configXml.getWebResponse().getContentCharset())); CopyJobCommand copyJobCommand = new CopyJobCommand(); copyJobCommand.setTransportAuth2(adminAuth); String pAdminName = pName + "-admin"; @@ -199,8 +199,8 @@ public void testExposedCiphertext() throws Exception { Authentication devAuth = User.get("dev").impersonate2(); getJobCommand.setTransportAuth2(devAuth); baos = new ByteArrayOutputStream(); - getJobCommand.main(Collections.singletonList(pName), Locale.ENGLISH, System.in, new PrintStream(baos), System.err); - assertEquals(xmlDev, baos.toString(configXml.getWebResponse().getContentCharset().name())); + getJobCommand.main(List.of(pName), Locale.ENGLISH, System.in, new PrintStream(baos), System.err); + assertEquals(xmlDev, baos.toString(configXml.getWebResponse().getContentCharset())); copyJobCommand = new CopyJobCommand(); copyJobCommand.setTransportAuth2(devAuth); String pDevName = pName + "-dev"; @@ -662,7 +662,7 @@ public Class type() { @NonNull @Override public Collection createFor(@NonNull Job target) { - return Collections.singletonList(new ActionImpl()); + return List.of(new ActionImpl()); } } diff --git a/test/src/test/java/org/kohsuke/stapler/Security1097Test.java b/test/src/test/java/org/kohsuke/stapler/Security1097Test.java index 90a7d70aa7df..51e09f159f7b 100644 --- a/test/src/test/java/org/kohsuke/stapler/Security1097Test.java +++ b/test/src/test/java/org/kohsuke/stapler/Security1097Test.java @@ -7,7 +7,7 @@ import hudson.model.RootAction; import java.lang.reflect.Field; import java.util.Arrays; -import java.util.Collections; +import java.util.List; import javax.servlet.ServletException; import net.sf.json.JSONObject; import org.junit.Rule; @@ -56,7 +56,7 @@ public void testGetWorksWithEscapeHatch() throws Exception { final HtmlPage htmlPage2 = webClient.goTo("security1097/get2"); j.submit(htmlPage2.getFormByName("config")); } finally { - allowed_http_verbs_for_forms.set(null, Collections.singletonList("POST")); + allowed_http_verbs_for_forms.set(null, List.of("POST")); } }