diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 3dc65e7dfbc2..76e53252891e 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -138,40 +138,45 @@ public static int _main(String[] _args) throws Exception { while (!args.isEmpty()) { String head = args.get(0); - if (head.equals("-version")) { - System.out.println("Version: " + computeVersion()); - return 0; - } - if (head.equals("-http")) { - if (mode != null) { - printUsage("-http clashes with previously defined mode " + mode); - return -1; + switch (head) { + case "-version" -> { + System.out.println("Version: " + computeVersion()); + return 0; } - mode = Mode.HTTP; - args = args.subList(1, args.size()); - continue; - } - if (head.equals("-ssh")) { - if (mode != null) { - printUsage("-ssh clashes with previously defined mode " + mode); - return -1; + case "-http" -> { + if (mode != null) { + printUsage("-http clashes with previously defined mode " + mode); + return -1; + } + mode = Mode.HTTP; + args = args.subList(1, args.size()); + continue; } - mode = Mode.SSH; - args = args.subList(1, args.size()); - continue; - } - if (head.equals("-webSocket")) { - if (mode != null) { - printUsage("-webSocket clashes with previously defined mode " + mode); + case "-ssh" -> { + if (mode != null) { + printUsage("-ssh clashes with previously defined mode " + mode); + return -1; + } + mode = Mode.SSH; + args = args.subList(1, args.size()); + continue; + } + case "-webSocket" -> { + if (mode != null) { + printUsage("-webSocket clashes with previously defined mode " + mode); + return -1; + } + mode = Mode.WEB_SOCKET; + args = args.subList(1, args.size()); + continue; + } + case "-remoting" -> { + printUsage("-remoting mode is no longer supported"); return -1; } - mode = Mode.WEB_SOCKET; - args = args.subList(1, args.size()); - continue; - } - if (head.equals("-remoting")) { - printUsage("-remoting mode is no longer supported"); - return -1; + default -> { + // continue + } } if (head.equals("-s") && args.size() >= 2) { url = args.get(1); diff --git a/cli/src/main/java/hudson/cli/PlainCLIProtocol.java b/cli/src/main/java/hudson/cli/PlainCLIProtocol.java index 4bd45b7b184e..59857540ce08 100644 --- a/cli/src/main/java/hudson/cli/PlainCLIProtocol.java +++ b/cli/src/main/java/hudson/cli/PlainCLIProtocol.java @@ -262,28 +262,33 @@ abstract static class ServerSide extends EitherSide { @Override protected final boolean handle(Op op, DataInputStream dis) throws IOException { assert op.clientSide; - switch (op) { - case ARG: - onArg(dis.readUTF()); - return true; - case LOCALE: - onLocale(dis.readUTF()); - return true; - case ENCODING: - onEncoding(dis.readUTF()); - return true; - case START: - onStart(); - return true; - case STDIN: - onStdin(dis.readAllBytes()); - return true; - case END_STDIN: - onEndStdin(); - return true; - default: - return false; - } + return switch (op) { + case ARG -> { + onArg(dis.readUTF()); + yield true; + } + case LOCALE -> { + onLocale(dis.readUTF()); + yield true; + } + case ENCODING -> { + onEncoding(dis.readUTF()); + yield true; + } + case START -> { + onStart(); + yield true; + } + case STDIN -> { + onStdin(dis.readAllBytes()); + yield true; + } + case END_STDIN -> { + onEndStdin(); + yield true; + } + default -> false; + }; } protected abstract void onArg(String text); @@ -321,19 +326,21 @@ abstract static class ClientSide extends EitherSide { @Override protected boolean handle(Op op, DataInputStream dis) throws IOException { assert !op.clientSide; - switch (op) { - case EXIT: - onExit(dis.readInt()); - return true; - case STDOUT: - onStdout(dis.readAllBytes()); - return true; - case STDERR: - onStderr(dis.readAllBytes()); - return true; - default: - return false; - } + return switch (op) { + case EXIT -> { + onExit(dis.readInt()); + yield true; + } + case STDOUT -> { + onStdout(dis.readAllBytes()); + yield true; + } + case STDERR -> { + onStderr(dis.readAllBytes()); + yield true; + } + default -> false; + }; } protected abstract void onExit(int code); diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 3d6ea7c42530..63c684e4a1e5 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -29,12 +29,10 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.util.QuotedStringTokenizer; import java.io.IOException; -import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.security.KeyPair; -import java.security.PublicKey; import java.util.List; import java.util.Set; import java.util.logging.Level; @@ -45,7 +43,6 @@ import org.apache.sshd.client.future.ConnectFuture; import org.apache.sshd.client.keyverifier.DefaultKnownHostsServerKeyVerifier; import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier; -import org.apache.sshd.client.keyverifier.ServerKeyVerifier; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.future.WaitableFuture; import org.apache.sshd.common.util.io.input.NoCloseInputStream; @@ -86,12 +83,9 @@ static int sshConnection(String jenkinsUrl, String user, List args, Priv try (SshClient client = SshClient.setUpDefaultClient()) { - KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier(new ServerKeyVerifier() { - @Override - public boolean verifyServerKey(ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey) { - CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString()); - return !strictHostKey; - } + KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier((clientSession, remoteAddress, serverKey) -> { + CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString()); + return !strictHostKey; }, true); client.setServerKeyVerifier(verifier); diff --git a/core/src/main/java/hudson/EnvVars.java b/core/src/main/java/hudson/EnvVars.java index 97def5f11a7f..f4164d7dfd6f 100644 --- a/core/src/main/java/hudson/EnvVars.java +++ b/core/src/main/java/hudson/EnvVars.java @@ -282,7 +282,7 @@ private void cutCycle(List cycle) { } // if not, cut the reference to the first one. - cutCycleAt(cycle.get(0), cycle); + cutCycleAt(cycle.getFirst(), cycle); } /** diff --git a/core/src/main/java/hudson/ExtensionFinder.java b/core/src/main/java/hudson/ExtensionFinder.java index 2fa4f34b941e..2893f6867ec4 100644 --- a/core/src/main/java/hudson/ExtensionFinder.java +++ b/core/src/main/java/hudson/ExtensionFinder.java @@ -628,7 +628,7 @@ public void onProvision(ProvisionInvocation provision) { .flatMap(Collection::stream) .filter(m -> m.getAnnotation(PostConstruct.class) != null || m.getAnnotation(javax.annotation.PostConstruct.class) != null) .findFirst() - .ifPresent(method -> methods.add(0, method)); + .ifPresent(methods::addFirst); c = c.getSuperclass(); } @@ -788,16 +788,12 @@ private Level logLevel(IndexItem item) { private static Class getClassFromIndex(IndexItem item) throws InstantiationException { AnnotatedElement e = item.element(); - Class extType; - if (e instanceof Class) { - extType = (Class) e; - } else if (e instanceof Field) { - extType = ((Field) e).getType(); - } else if (e instanceof Method) { - extType = ((Method) e).getReturnType(); - } else { - throw new AssertionError(); - } + Class extType = switch (e) { + case Class aClass -> aClass; + case Field field -> field.getType(); + case Method method -> method.getReturnType(); + case null, default -> throw new AssertionError(); + }; return extType; } diff --git a/core/src/main/java/hudson/ExtensionList.java b/core/src/main/java/hudson/ExtensionList.java index badef0da2089..bbdd259d6f46 100644 --- a/core/src/main/java/hudson/ExtensionList.java +++ b/core/src/main/java/hudson/ExtensionList.java @@ -457,7 +457,7 @@ public static ExtensionList create(Jenkins jenkins, Class type) { } else if (all.size() != 1) { throw new IllegalStateException("Expected 1 instance of " + type.getName() + " but got " + all.size()); } - return all.get(0); + return all.getFirst(); } /** @@ -474,7 +474,7 @@ public static ExtensionList create(Jenkins jenkins, Class type) { public static @NonNull U lookupFirst(Class type) { var all = lookup(type); if (!all.isEmpty()) { - return all.get(0); + return all.getFirst(); } else { if (Main.isUnitTest) { throw new IllegalStateException("Found no instances of " + type.getName() + diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index ca35c97aed9a..78c191966a20 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -350,15 +350,15 @@ public static String normalize(@NonNull String path) { if (i == 0) { // If absolute path, just remove: /../something // If relative path, not collapsible so leave as-is - tokens.remove(0); - if (!tokens.isEmpty()) token += tokens.remove(0); + tokens.removeFirst(); + if (!tokens.isEmpty()) token += tokens.removeFirst(); if (!isAbsolute) buf.append(token); } else { // Normalize: remove something/.. plus separator before/after i -= 2; for (int j = 0; j < 3; j++) tokens.remove(i); if (i > 0) tokens.remove(i - 1); - else if (!tokens.isEmpty()) tokens.remove(0); + else if (!tokens.isEmpty()) tokens.removeFirst(); } } else i += 2; diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index fbd5e8a64d94..57b4d72e61da 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -142,6 +142,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedMap; @@ -1278,11 +1279,7 @@ public static boolean hasAnyPermission(Object object, Permission[] permissions) return hasAnyPermission((AccessControlled) object, permissions); else { AccessControlled ac = Stapler.getCurrentRequest2().findAncestorObject(AccessControlled.class); - if (ac != null) { - return hasAnyPermission(ac, permissions); - } - - return hasAnyPermission(Jenkins.get(), permissions); + return hasAnyPermission(Objects.requireNonNullElseGet(ac, Jenkins::get), permissions); } } diff --git a/core/src/main/java/hudson/MarkupText.java b/core/src/main/java/hudson/MarkupText.java index 182565205ecf..11149208de1f 100644 --- a/core/src/main/java/hudson/MarkupText.java +++ b/core/src/main/java/hudson/MarkupText.java @@ -266,7 +266,7 @@ public void addMarkup(int startPos, int endPos, String startTag, String endTag) // abc, not abc. Also, we'd like abcdef, // not abcdef. Do this by inserting them to different places. tags.add(new Tag(startPos, startTag)); - tags.add(0, new Tag(endPos, endTag)); + tags.addFirst(new Tag(endPos, endTag)); } public void addMarkup(int pos, String tag) { diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index c4dcaf1f2825..f1b7a7bbd776 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -583,56 +583,47 @@ public void run(Reactor session) throws Exception { // schedule execution of loading plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[0])) { - g.followedBy().notFatal().attains(PLUGINS_PREPARED).add(String.format("Loading plugin %s v%s (%s)", p.getLongName(), p.getVersion(), p.getShortName()), new Executable() { - @Override - public void run(Reactor session) throws Exception { - try { - p.resolvePluginDependencies(); - strategy.load(p); - } catch (MissingDependencyException e) { - failedPlugins.add(new FailedPlugin(p, e)); - activePlugins.remove(p); - plugins.remove(p); - p.releaseClassLoader(); - LOGGER.log(Level.SEVERE, "Failed to install {0}: {1}", new Object[] { p.getShortName(), e.getMessage() }); - } catch (IOException e) { - failedPlugins.add(new FailedPlugin(p, e)); - activePlugins.remove(p); - plugins.remove(p); - p.releaseClassLoader(); - throw e; - } + g.followedBy().notFatal().attains(PLUGINS_PREPARED).add(String.format("Loading plugin %s v%s (%s)", p.getLongName(), p.getVersion(), p.getShortName()), reactor -> { + try { + p.resolvePluginDependencies(); + strategy.load(p); + } catch (MissingDependencyException e) { + failedPlugins.add(new FailedPlugin(p, e)); + activePlugins.remove(p); + plugins.remove(p); + p.releaseClassLoader(); + LOGGER.log(Level.SEVERE, "Failed to install {0}: {1}", new Object[] { p.getShortName(), e.getMessage() }); + } catch (IOException e) { + failedPlugins.add(new FailedPlugin(p, e)); + activePlugins.remove(p); + plugins.remove(p); + p.releaseClassLoader(); + throw e; } }); } // schedule execution of initializing plugins for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[0])) { - g.followedBy().notFatal().attains(PLUGINS_STARTED).add("Initializing plugin " + p.getShortName(), new Executable() { - @Override - public void run(Reactor session) throws Exception { - if (!activePlugins.contains(p)) { - return; - } - try { - p.getPluginOrFail().postInitialize(); - } catch (Exception e) { - failedPlugins.add(new FailedPlugin(p, e)); - activePlugins.remove(p); - plugins.remove(p); - p.releaseClassLoader(); - throw e; - } + g.followedBy().notFatal().attains(PLUGINS_STARTED).add("Initializing plugin " + p.getShortName(), reactor -> { + if (!activePlugins.contains(p)) { + return; + } + try { + p.getPluginOrFail().postInitialize(); + } catch (Exception e) { + failedPlugins.add(new FailedPlugin(p, e)); + activePlugins.remove(p); + plugins.remove(p); + p.releaseClassLoader(); + throw e; } }); } - g.followedBy().attains(PLUGINS_STARTED).add("Discovering plugin initialization tasks", new Executable() { - @Override - public void run(Reactor reactor) throws Exception { - // rescan to find plugin-contributed @Initializer - reactor.addAll(initializerFinder.discoverTasks(reactor)); - } + g.followedBy().attains(PLUGINS_STARTED).add("Discovering plugin initialization tasks", reactor -> { + // rescan to find plugin-contributed @Initializer + reactor.addAll(initializerFinder.discoverTasks(reactor)); }); // register them all @@ -641,12 +632,7 @@ public void run(Reactor reactor) throws Exception { }); // All plugins are loaded. Now we can figure out who depends on who. - requires(PLUGINS_PREPARED).attains(COMPLETED).add("Resolving Dependent Plugins Graph", new Executable() { - @Override - public void run(Reactor reactor) throws Exception { - resolveDependentPlugins(); - } - }); + requires(PLUGINS_PREPARED).attains(COMPLETED).add("Resolving Dependent Plugins Graph", reactor -> resolveDependentPlugins()); }}); } @@ -813,35 +799,32 @@ protected void loadDetachedPlugins() { final List detachedPlugins = DetachedPluginsUtil.getDetachedPlugins(lastExecVersion); - Set loadedDetached = loadPluginsFromWar(getDetachedLocation(), new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - name = normalisePluginName(name); - - // If this was a plugin that was detached some time in the past i.e. not just one of the - // plugins that was bundled "for fun". - if (DetachedPluginsUtil.isDetachedPlugin(name)) { - VersionNumber installedVersion = getPluginVersion(rootDir, name); - VersionNumber bundledVersion = getPluginVersion(dir, name); - // If the plugin is already installed, we need to decide whether to replace it with the bundled version. - if (installedVersion != null && bundledVersion != null) { - // If the installed version is older than the bundled version, then it MUST be upgraded. - // If the installed version is newer than the bundled version, then it MUST NOT be upgraded. - // If the versions are equal we just keep the installed version. - return installedVersion.isOlderThan(bundledVersion); - } + Set loadedDetached = loadPluginsFromWar(getDetachedLocation(), (dir, name) -> { + name = normalisePluginName(name); + + // If this was a plugin that was detached some time in the past i.e. not just one of the + // plugins that was bundled "for fun". + if (DetachedPluginsUtil.isDetachedPlugin(name)) { + VersionNumber installedVersion = getPluginVersion(rootDir, name); + VersionNumber bundledVersion = getPluginVersion(dir, name); + // If the plugin is already installed, we need to decide whether to replace it with the bundled version. + if (installedVersion != null && bundledVersion != null) { + // If the installed version is older than the bundled version, then it MUST be upgraded. + // If the installed version is newer than the bundled version, then it MUST NOT be upgraded. + // If the versions are equal we just keep the installed version. + return installedVersion.isOlderThan(bundledVersion); } + } - // If it's a plugin that was detached since the last running version. - for (DetachedPluginsUtil.DetachedPlugin detachedPlugin : detachedPlugins) { - if (detachedPlugin.getShortName().equals(name)) { - return true; - } + // If it's a plugin that was detached since the last running version. + for (DetachedPluginsUtil.DetachedPlugin detachedPlugin : detachedPlugins) { + if (detachedPlugin.getShortName().equals(name)) { + return true; } - - // Otherwise skip this and do not install. - return false; } + + // Otherwise skip this and do not install. + return false; }); LOGGER.log(INFO, "Upgraded Jenkins from version {0} to version {1}. Loaded detached plugins (and dependencies): {2}", @@ -860,17 +843,14 @@ public boolean accept(File dir, String name) { } } if (!forceUpgrade.isEmpty()) { - Set loadedDetached = loadPluginsFromWar(getDetachedLocation(), new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - name = normalisePluginName(name); - for (DetachedPluginsUtil.DetachedPlugin detachedPlugin : forceUpgrade) { - if (detachedPlugin.getShortName().equals(name)) { - return true; - } + Set loadedDetached = loadPluginsFromWar(getDetachedLocation(), (dir, name) -> { + name = normalisePluginName(name); + for (DetachedPluginsUtil.DetachedPlugin detachedPlugin : forceUpgrade) { + if (detachedPlugin.getShortName().equals(name)) { + return true; } - return false; } + return false; }); LOGGER.log(INFO, "Upgraded detached plugins (and dependencies): {0}", new Object[]{loadedDetached}); @@ -1170,8 +1150,7 @@ protected void copyBundledPlugin(URL src, String fileName) throws IOException { InputStream in = null; // Magic, which allows to avoid using stream generated for JarURLConnection. // It prevents getting into JENKINS-37332 due to the file descriptor leak - if (uc instanceof JarURLConnection) { - final JarURLConnection jarURLConnection = (JarURLConnection) uc; + if (uc instanceof JarURLConnection jarURLConnection) { final String entryName = jarURLConnection.getEntryName(); try (JarFile jarFile = jarURLConnection.getJarFile()) { @@ -1211,8 +1190,7 @@ protected void copyBundledPlugin(URL src, String fileName) throws IOException { // It prevents file descriptor leak if the URL references a file within JAR // See JENKINS-37332 for more info // The code idea is taken from https://github.com/jknack/handlebars.java/pull/394 - if (uc instanceof JarURLConnection) { - final JarURLConnection connection = (JarURLConnection) uc; + if (uc instanceof JarURLConnection connection) { final URL jarURL = connection.getJarFileURL(); if (jarURL.getProtocol().equals("file")) { String file = jarURL.getFile(); @@ -1793,37 +1771,34 @@ private List> install(@NonNull Collection jobFuture : installJobs) { - if (!jobFuture.isDone() && !jobFuture.isCancelled()) { - continue INSTALLING; - } - UpdateCenter.UpdateCenterJob job = jobFuture.get(); - if (job instanceof InstallationJob && ((InstallationJob) job).status instanceof DownloadJob.Failure) { - failures = true; - } + new Thread(() -> { + boolean failures = false; + INSTALLING: while (true) { + try { + updateCenter.persistInstallStatus(); + Thread.sleep(500); + failures = false; + for (Future jobFuture : installJobs) { + if (!jobFuture.isDone() && !jobFuture.isCancelled()) { + continue INSTALLING; + } + UpdateCenter.UpdateCenterJob job = jobFuture.get(); + if (job instanceof InstallationJob && ((InstallationJob) job).status instanceof DownloadJob.Failure) { + failures = true; } - } catch (Exception e) { - LOGGER.log(WARNING, "Unexpected error while waiting for initial plugin set to install.", e); } - break; + } catch (Exception e) { + LOGGER.log(WARNING, "Unexpected error while waiting for initial plugin set to install.", e); } - updateCenter.persistInstallStatus(); - if (!failures) { - try (ACLContext acl = ACL.as2(currentAuth)) { - InstallUtil.proceedToNextStateFrom(InstallState.INITIAL_PLUGINS_INSTALLING); - } + break; + } + updateCenter.persistInstallStatus(); + if (!failures) { + try (ACLContext acl = ACL.as2(currentAuth)) { + InstallUtil.proceedToNextStateFrom(InstallState.INITIAL_PLUGINS_INSTALLING); } } - }.start(); + }).start(); } return installJobs; @@ -1956,7 +1931,7 @@ private HttpResponse doUploadPluginImpl(StaplerRequest2 req) throws IOException, copier = new UrlPluginCopier(fileName); } else { // this is a file upload - FileItem fileItem = items.get(0); + FileItem fileItem = items.getFirst(); fileName = Util.getFileName(fileItem.getName()); copier = new FileUploadPluginCopier(fileItem); } @@ -2675,7 +2650,7 @@ public Map getDeprecatedPlugins() { .filter(PluginWrapper::isDeprecated) .sorted(Comparator.comparing(PluginWrapper::getDisplayName)) // Sort by plugin name .collect(LinkedHashMap::new, - (map, plugin) -> map.put(plugin, plugin.getDeprecations().get(0).url), + (map, plugin) -> map.put(plugin, plugin.getDeprecations().getFirst().url), Map::putAll); } } diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java index 41e010a92d6d..a77df0d3bca6 100644 --- a/core/src/main/java/hudson/PluginWrapper.java +++ b/core/src/main/java/hudson/PluginWrapper.java @@ -633,7 +633,7 @@ public String getUrl() { List siteMetadataList = getInfoFromAllSites(); String firstSiteUrl = null; if (!siteMetadataList.isEmpty()) { - firstSiteUrl = siteMetadataList.get(0).wiki; + firstSiteUrl = siteMetadataList.getFirst().wiki; if (allUrlsMatch(firstSiteUrl, siteMetadataList)) { return firstSiteUrl; } @@ -878,18 +878,16 @@ private void disableWithoutCheck() throws IOException { } private Set dependentsToCheck(PluginDisableStrategy strategy) { - Set dependentsToCheck; - switch (strategy) { - case ALL: + Set dependentsToCheck = switch (strategy) { + case ALL -> // getDependents returns all the dependent plugins, mandatory or optional. - dependentsToCheck = this.getDependents(); - break; - default: + this.getDependents(); + default -> // It includes MANDATORY, NONE: // with NONE, the process only fail if mandatory dependent plugins exists // As of getDependents has all the dependents, we get the difference between them and only the optionals - dependentsToCheck = Sets.difference(this.getDependents(), this.getOptionalDependents()); - } + Sets.difference(this.getDependents(), this.getOptionalDependents()); + }; return dependentsToCheck; } diff --git a/core/src/main/java/hudson/Proc.java b/core/src/main/java/hudson/Proc.java index a36ac726ec5c..ec0357d20bb6 100644 --- a/core/src/main/java/hudson/Proc.java +++ b/core/src/main/java/hudson/Proc.java @@ -155,18 +155,15 @@ public final int joinWithTimeout(final long timeout, final TimeUnit unit, final TaskListener listener) throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); try { - executor.submit(new Runnable() { - @Override - public void run() { - try { - if (!latch.await(timeout, unit)) { - listener.error("Timeout after " + timeout + " " + - unit.toString().toLowerCase(Locale.ENGLISH)); - kill(); - } - } catch (InterruptedException | IOException | RuntimeException x) { - Functions.printStackTrace(x, listener.error("Failed to join a process")); + executor.submit(() -> { + try { + if (!latch.await(timeout, unit)) { + listener.error("Timeout after " + timeout + " " + + unit.toString().toLowerCase(Locale.ENGLISH)); + kill(); } + } catch (InterruptedException | IOException | RuntimeException x) { + Functions.printStackTrace(x, listener.error("Failed to join a process")); } }); return join(); diff --git a/core/src/main/java/hudson/StructuredForm.java b/core/src/main/java/hudson/StructuredForm.java index 286e79997652..cecf0a694978 100644 --- a/core/src/main/java/hudson/StructuredForm.java +++ b/core/src/main/java/hudson/StructuredForm.java @@ -64,13 +64,12 @@ public static JSONObject get(StaplerRequest req) throws ServletException { public static List toList(JSONObject parent, String propertyName) { Object v = parent.get(propertyName); - if (v == null) - return Collections.emptyList(); - if (v instanceof JSONObject) - return List.of((JSONObject) v); - if (v instanceof JSONArray) - return (List) v; + return switch (v) { + case null -> Collections.emptyList(); + case JSONObject jsonObject -> List.of(jsonObject); + case JSONArray objects -> (List) v; + default -> throw new IllegalArgumentException(); + }; - throw new IllegalArgumentException(); } } diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index 9a2377550b5b..b4743f6cf3ba 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -212,8 +212,7 @@ public void shutdown() { shuttingDown = true; try { SocketAddress localAddress = serverSocket.getLocalAddress(); - if (localAddress instanceof InetSocketAddress) { - InetSocketAddress address = (InetSocketAddress) localAddress; + if (localAddress instanceof InetSocketAddress address) { Socket client = new Socket(address.getHostName(), address.getPort()); client.setSoTimeout(1000); // waking the acceptor loop should be quick new PingAgentProtocol().connect(client); @@ -229,10 +228,12 @@ public void shutdown() { } private final class ConnectionHandler extends Thread { - private static final String DEFAULT_RESPONSE_404 = "HTTP/1.0 404 Not Found\r\n" + - "Content-Type: text/plain;charset=UTF-8\r\n" + - "\r\n" + - "Not Found\r\n"; + private static final String DEFAULT_RESPONSE_404 = """ + HTTP/1.0 404 Not Found + Content-Type: text/plain;charset=UTF-8 + + Not Found + """; private final Socket s; /** * Unique number to identify this connection. Used in the log. diff --git a/core/src/main/java/hudson/XmlFile.java b/core/src/main/java/hudson/XmlFile.java index 91d96959b61d..65b21ad75835 100644 --- a/core/src/main/java/hudson/XmlFile.java +++ b/core/src/main/java/hudson/XmlFile.java @@ -351,8 +351,7 @@ public void startElement(String uri, String localName, String qName, Attributes private void attempt() throws Eureka { if (loc == null) return; - if (loc instanceof Locator2) { - Locator2 loc2 = (Locator2) loc; + if (loc instanceof Locator2 loc2) { String e = loc2.getEncoding(); if (e != null) throw new Eureka(e); diff --git a/core/src/main/java/hudson/cli/BuildCommand.java b/core/src/main/java/hudson/cli/BuildCommand.java index b4f7ae15e0a1..58f80ad0a032 100644 --- a/core/src/main/java/hudson/cli/BuildCommand.java +++ b/core/src/main/java/hudson/cli/BuildCommand.java @@ -222,18 +222,19 @@ protected int run() throws Exception { @Override protected void printUsageSummary(PrintStream stderr) { stderr.println( - "Starts a build, and optionally waits for a completion.\n" + - "Aside from general scripting use, this command can be\n" + - "used to invoke another job from within a build of one job.\n" + - "With the -s option, this command changes the exit code based on\n" + - "the outcome of the build (exit code 0 indicates a success)\n" + - "and interrupting the command will interrupt the job.\n" + - "With the -f option, this command changes the exit code based on\n" + - "the outcome of the build (exit code 0 indicates a success)\n" + - "however, unlike -s, interrupting the command will not interrupt\n" + - "the job (exit code 125 indicates the command was interrupted).\n" + - "With the -c option, a build will only run if there has been\n" + - "an SCM change." + """ + Starts a build, and optionally waits for a completion. + Aside from general scripting use, this command can be + used to invoke another job from within a build of one job. + With the -s option, this command changes the exit code based on + the outcome of the build (exit code 0 indicates a success) + and interrupting the command will interrupt the job. + With the -f option, this command changes the exit code based on + the outcome of the build (exit code 0 indicates a success) + however, unlike -s, interrupting the command will not interrupt + the job (exit code 125 indicates the command was interrupted). + With the -c option, a build will only run if there has been + an SCM change.""" ); } diff --git a/core/src/main/java/hudson/cli/CLIAction.java b/core/src/main/java/hudson/cli/CLIAction.java index 4538d857d4d3..512729215844 100644 --- a/core/src/main/java/hudson/cli/CLIAction.java +++ b/core/src/main/java/hudson/cli/CLIAction.java @@ -331,7 +331,7 @@ void run() throws IOException, InterruptedException { sendExit(2); return; } - String commandName = args.get(0); + String commandName = args.getFirst(); CLICommand command = CLICommand.clone(commandName); if (command == null) { stderr.println("No such command " + commandName); diff --git a/core/src/main/java/hudson/cli/CLICommand.java b/core/src/main/java/hudson/cli/CLICommand.java index 8e0897804537..b1754e801115 100644 --- a/core/src/main/java/hudson/cli/CLICommand.java +++ b/core/src/main/java/hudson/cli/CLICommand.java @@ -277,30 +277,38 @@ public int main(List args, Locale locale, InputStream stdin, PrintStream * */ protected int handleException(Throwable e, CLIContext context, CmdLineParser p) { int exitCode; - if (e instanceof CmdLineException) { - exitCode = 2; - printError(e.getMessage()); - printUsage(stderr, p); - } else if (e instanceof IllegalArgumentException) { - exitCode = 3; - printError(e.getMessage()); - } else if (e instanceof IllegalStateException) { - exitCode = 4; - printError(e.getMessage()); - } else if (e instanceof AbortException) { - exitCode = 5; - printError(e.getMessage()); - } else if (e instanceof AccessDeniedException) { - exitCode = 6; - printError(e.getMessage()); - } else if (e instanceof BadCredentialsException) { - exitCode = 7; - printError( - "Bad Credentials. Search the server log for " + context.getCorrelationId() + " for more details."); - } else { - exitCode = 1; - printError("Unexpected exception occurred while performing " + getName() + " command."); - Functions.printStackTrace(e, stderr); + switch (e) { + case CmdLineException cmdLineException -> { + exitCode = 2; + printError(e.getMessage()); + printUsage(stderr, p); + } + case IllegalArgumentException illegalArgumentException -> { + exitCode = 3; + printError(e.getMessage()); + } + case IllegalStateException illegalStateException -> { + exitCode = 4; + printError(e.getMessage()); + } + case AbortException abortException -> { + exitCode = 5; + printError(e.getMessage()); + } + case AccessDeniedException accessDeniedException -> { + exitCode = 6; + printError(e.getMessage()); + } + case BadCredentialsException badCredentialsException -> { + exitCode = 7; + printError( + "Bad Credentials. Search the server log for " + context.getCorrelationId() + " for more details."); + } + case null, default -> { + exitCode = 1; + printError("Unexpected exception occurred while performing " + getName() + " command."); + Functions.printStackTrace(e, stderr); + } } return exitCode; } diff --git a/core/src/main/java/hudson/cli/DisablePluginCommand.java b/core/src/main/java/hudson/cli/DisablePluginCommand.java index 1b42d497f092..03f14ee9ddf2 100644 --- a/core/src/main/java/hudson/cli/DisablePluginCommand.java +++ b/core/src/main/java/hudson/cli/DisablePluginCommand.java @@ -46,10 +46,11 @@ public class DisablePluginCommand extends CLICommand { @Option(name = "-restart", aliases = "-r", usage = "Restart Jenkins after disabling plugins.") private boolean restart; - @Option(name = "-strategy", aliases = "-s", metaVar = "strategy", usage = "How to process the dependent plugins. \n" + - "- none: if a mandatory dependent plugin exists and it is enabled, the plugin cannot be disabled (default value).\n" + - "- mandatory: all mandatory dependent plugins are also disabled, optional dependent plugins remain enabled.\n" + - "- all: all dependent plugins are also disabled, no matter if its dependency is optional or mandatory.") + @Option(name = "-strategy", aliases = "-s", metaVar = "strategy", usage = """ + How to process the dependent plugins. + - none: if a mandatory dependent plugin exists and it is enabled, the plugin cannot be disabled (default value). + - mandatory: all mandatory dependent plugins are also disabled, optional dependent plugins remain enabled. + - all: all dependent plugins are also disabled, no matter if its dependency is optional or mandatory.""") private String strategy = PluginWrapper.PluginDisableStrategy.NONE.toString(); @Option(name = "-quiet", aliases = "-q", usage = "Be quiet, print only the error messages") diff --git a/core/src/main/java/hudson/cli/declarative/MethodBinder.java b/core/src/main/java/hudson/cli/declarative/MethodBinder.java index 91dfd11da7f0..8620f218076a 100644 --- a/core/src/main/java/hudson/cli/declarative/MethodBinder.java +++ b/core/src/main/java/hudson/cli/declarative/MethodBinder.java @@ -179,10 +179,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof ArgumentImpl)) { + if (!(o instanceof ArgumentImpl argument)) { return false; } - ArgumentImpl argument = (ArgumentImpl) o; return Objects.equals(base, argument.base) && bias == argument.bias; } diff --git a/core/src/main/java/hudson/console/ConsoleAnnotator.java b/core/src/main/java/hudson/console/ConsoleAnnotator.java index be66242a9d84..4b443dbda4c9 100644 --- a/core/src/main/java/hudson/console/ConsoleAnnotator.java +++ b/core/src/main/java/hudson/console/ConsoleAnnotator.java @@ -112,11 +112,11 @@ public ConsoleAnnotator annotate(T context, MarkupText text) { } } - switch (list.size()) { - case 0: return null; // no more annotator left - case 1: return list.get(0); // no point in aggregating - default: return this; - } + return switch (list.size()) { + case 0 -> null; // no more annotator left + case 1 -> list.getFirst(); // no point in aggregating + default -> this; + }; } @Override @@ -129,11 +129,11 @@ public String toString() { * Bundles all the given {@link ConsoleAnnotator} into a single annotator. */ public static ConsoleAnnotator combine(Collection> all) { - switch (all.size()) { - case 0: return null; // none - case 1: return cast(all.iterator().next()); // just one - default: return new ConsoleAnnotatorAggregator<>(all); - } + return switch (all.size()) { + case 0 -> null; // none + case 1 -> cast(all.iterator().next()); // just one + default -> new ConsoleAnnotatorAggregator<>(all); + }; } /** diff --git a/core/src/main/java/hudson/lifecycle/Lifecycle.java b/core/src/main/java/hudson/lifecycle/Lifecycle.java index 3fd86157f226..8a54593ff6aa 100644 --- a/core/src/main/java/hudson/lifecycle/Lifecycle.java +++ b/core/src/main/java/hudson/lifecycle/Lifecycle.java @@ -93,16 +93,12 @@ public static synchronized Lifecycle get() { instance = new PlaceholderLifecycle(); } catch (InvocationTargetException e) { Throwable t = e.getCause(); - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else if (t instanceof IOException) { - throw new UncheckedIOException((IOException) t); - } else if (t instanceof Exception) { - throw new RuntimeException(t); - } else if (t instanceof Error) { - throw (Error) t; - } else { - throw new Error(e); + switch (t) { + case RuntimeException runtimeException -> throw runtimeException; + case IOException ioException -> throw new UncheckedIOException(ioException); + case Exception exception -> throw new RuntimeException(t); + case Error error -> throw error; + case null, default -> throw new Error(e); } } } else { diff --git a/core/src/main/java/hudson/lifecycle/UnixLifecycle.java b/core/src/main/java/hudson/lifecycle/UnixLifecycle.java index cb314465d09b..92d08870e94a 100644 --- a/core/src/main/java/hudson/lifecycle/UnixLifecycle.java +++ b/core/src/main/java/hudson/lifecycle/UnixLifecycle.java @@ -80,7 +80,7 @@ public void restart() throws IOException, InterruptedException { } // exec to self - String exe = args.get(0); + String exe = args.getFirst(); LIBC.execvp(exe, new StringArray(args.toArray(new String[0]))); throw new IOException("Failed to exec '" + exe + "' " + LIBC.strerror(Native.getLastError())); } diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index 4f2b5306b1ad..5cbe2500979a 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -75,7 +75,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -1196,18 +1195,13 @@ public RangeSet getDownstreamRelationship(AbstractProject that) { public Iterable> getDownstreamBuilds(final AbstractProject that) { final Iterable nums = getDownstreamRelationship(that).listNumbers(); - return new Iterable<>() { - @Override - public Iterator> iterator() { - return Iterators.removeNull( - new AdaptedIterator<>(nums) { - @Override - protected AbstractBuild adapt(Integer item) { - return that.getBuildByNumber(item); - } - }); - } - }; + return () -> Iterators.removeNull( + new AdaptedIterator<>(nums) { + @Override + protected AbstractBuild adapt(Integer item) { + return that.getBuildByNumber(item); + } + }); } /** diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java index 8c2561566032..43599ab97d19 100644 --- a/core/src/main/java/hudson/model/AbstractItem.java +++ b/core/src/main/java/hudson/model/AbstractItem.java @@ -546,7 +546,7 @@ public final String getUrl() { } List ancestors = req.getAncestors(); if (!ancestors.isEmpty()) { - Ancestor last = ancestors.get(ancestors.size() - 1); + Ancestor last = ancestors.getLast(); if (last.getObject() instanceof View view) { if (view.getOwner().getItemGroup() == getParent() && !view.isDefault()) { // Showing something inside a view, so should use that as the base URL. diff --git a/core/src/main/java/hudson/model/Api.java b/core/src/main/java/hudson/model/Api.java index 4b16e1b0b540..b86017ee448a 100644 --- a/core/src/main/java/hudson/model/Api.java +++ b/core/src/main/java/hudson/model/Api.java @@ -179,7 +179,7 @@ public void doXml(StaplerRequest2 req, StaplerResponse2 rsp, rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size())); return; } else { - result = list.get(0); + result = list.getFirst(); } } diff --git a/core/src/main/java/hudson/model/Cause.java b/core/src/main/java/hudson/model/Cause.java index ecad4e8c53b9..feb439a9d90d 100644 --- a/core/src/main/java/hudson/model/Cause.java +++ b/core/src/main/java/hudson/model/Cause.java @@ -202,12 +202,11 @@ private UpstreamCause(String upstreamProject, int upstreamBuild, String upstream @Override public void onLoad(@NonNull Job _job, int _buildNumber) { Item i = Jenkins.get().getItemByFullName(this.upstreamProject); - if (!(i instanceof Job)) { + if (!(i instanceof Job j)) { // cannot initialize upstream causes return; } - Job j = (Job) i; for (Cause c : this.upstreamCauses) { c.onLoad(j, upstreamBuild); } @@ -221,9 +220,7 @@ public boolean equals(Object rhs) { if (this == rhs) return true; - if (!(rhs instanceof UpstreamCause)) return false; - - final UpstreamCause o = (UpstreamCause) rhs; + if (!(rhs instanceof UpstreamCause o)) return false; return Objects.equals(upstreamBuild, o.upstreamBuild) && Objects.equals(upstreamCauses, o.upstreamCauses) && @@ -240,10 +237,9 @@ public int hashCode() { } private @NonNull Cause trim(@NonNull Cause c, int depth, Set traversed) { - if (!(c instanceof UpstreamCause)) { + if (!(c instanceof UpstreamCause uc)) { return c; } - UpstreamCause uc = (UpstreamCause) c; List cs = new ArrayList<>(); if (traversed.add(uc.upstreamUrl + uc.upstreamBuild)) { for (Cause c2 : uc.upstreamCauses) { diff --git a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java index 98bdcf2e8072..ffa55d56289e 100644 --- a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java +++ b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java @@ -116,8 +116,7 @@ private void setChoicesText(@NonNull String choices) { @Override public ParameterDefinition copyWithDefaultValue(ParameterValue defaultValue) { - if (defaultValue instanceof StringParameterValue) { - StringParameterValue value = (StringParameterValue) defaultValue; + if (defaultValue instanceof StringParameterValue value) { return new ChoiceParameterDefinition(getName(), choices, value.value, getDescription()); } else { return this; @@ -141,7 +140,7 @@ public StringParameterValue getDefaultParameterValue() { if (choices.isEmpty()) { return null; } - return new StringParameterValue(getName(), choices.get(0), getDescription()); + return new StringParameterValue(getName(), choices.getFirst(), getDescription()); } return new StringParameterValue(getName(), defaultValue, getDescription()); } diff --git a/core/src/main/java/hudson/model/DependencyGraph.java b/core/src/main/java/hudson/model/DependencyGraph.java index aa9810792a55..f19906d6311e 100644 --- a/core/src/main/java/hudson/model/DependencyGraph.java +++ b/core/src/main/java/hudson/model/DependencyGraph.java @@ -258,8 +258,7 @@ public void addDependency(Collection upstream, Abstra */ public void addDependencyDeclarers(AbstractProject upstream, Collection possibleDependecyDeclarers) { for (Object o : possibleDependecyDeclarers) { - if (o instanceof DependencyDeclarer) { - DependencyDeclarer dd = (DependencyDeclarer) o; + if (o instanceof DependencyDeclarer dd) { dd.buildDependencyGraph(upstream, this); } } @@ -342,13 +341,7 @@ private Map> finalize(Map NAME_COMPARATOR = new Comparator<>() { - @Override - public int compare(DependencyGroup lhs, DependencyGroup rhs) { - int cmp = lhs.getUpstreamProject().getName().compareTo(rhs.getUpstreamProject().getName()); - return cmp != 0 ? cmp : lhs.getDownstreamProject().getName().compareTo(rhs.getDownstreamProject().getName()); - } - }; + private static final Comparator NAME_COMPARATOR = Comparator.comparing((DependencyGroup lhs) -> lhs.getUpstreamProject().getName()).thenComparing(lhs -> lhs.getDownstreamProject().getName()); public static final DependencyGraph EMPTY = new DependencyGraph(false); diff --git a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java index 07be207fc012..d1f211ad4136 100644 --- a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java +++ b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java @@ -800,9 +800,9 @@ private static List> buildChildPaths(VirtualFile cur, Locale locale) sub.add(vf); } } - if (sub.size() != 1 || !sub.get(0).isDirectory()) + if (sub.size() != 1 || !sub.getFirst().isDirectory()) break; - f = sub.get(0); + f = sub.getFirst(); relPath += '/' + Util.rawEncode(f.getName()); l.add(new Path(relPath, f.getName(), true, f.length(), f.canRead(), f.lastModified())); } diff --git a/core/src/main/java/hudson/model/DisplayNameListener.java b/core/src/main/java/hudson/model/DisplayNameListener.java index 2aee0c035c17..569947e659ca 100644 --- a/core/src/main/java/hudson/model/DisplayNameListener.java +++ b/core/src/main/java/hudson/model/DisplayNameListener.java @@ -50,8 +50,7 @@ public class DisplayNameListener extends ItemListener { @Override public void onCopied(Item src, Item item) { // bug 5056825 - Display name field should be cleared when you copy a job within the same folder. - if (item instanceof AbstractItem && src.getParent() == item.getParent()) { - AbstractItem dest = (AbstractItem) item; + if (item instanceof AbstractItem dest && src.getParent() == item.getParent()) { try { dest.setDisplayName(null); } catch (IOException ioe) { @@ -71,8 +70,7 @@ public void onCopied(Item src, Item item) { @Override public void onRenamed(Item item, String oldName, String newName) { // bug 5077308 - Display name field should be cleared when you rename a job. - if (item instanceof AbstractItem) { - AbstractItem abstractItem = (AbstractItem) item; + if (item instanceof AbstractItem abstractItem) { if (oldName.equals(abstractItem.getDisplayName())) { // the user renamed the job, but the old project name which is shown as the // displayname if no displayname was set, has been set into the displayname field. diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index 0988b36785dd..5dd45967dc75 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -420,7 +420,7 @@ public FormValidation updateNow() throws IOException { * @return a single JSONObject */ public JSONObject reduce(List jsonList) { - return jsonList.get(0); + return jsonList.getFirst(); } /** @@ -436,9 +436,9 @@ public static boolean hasDuplicates(List genericList, String comparator) } Field field; try { - field = genericList.get(0).getClass().getDeclaredField(comparator); + field = genericList.getFirst().getClass().getDeclaredField(comparator); } catch (NoSuchFieldException e) { - LOGGER.warning("comparator: " + comparator + "does not exist for " + genericList.get(0).getClass() + ", " + e); + LOGGER.warning("comparator: " + comparator + " does not exist for " + genericList.getFirst().getClass() + ", " + e); return false; } for (int i = 0; i < genericList.size(); i++) { diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java index 3131e67a83a4..9286fa53602b 100644 --- a/core/src/main/java/hudson/model/Executor.java +++ b/core/src/main/java/hudson/model/Executor.java @@ -589,8 +589,7 @@ public FilePath getCurrentWorkspace() { if (executable == null) { return null; } - if (executable instanceof AbstractBuild) { - AbstractBuild ab = (AbstractBuild) executable; + if (executable instanceof AbstractBuild ab) { return ab.getWorkspace(); } return null; diff --git a/core/src/main/java/hudson/model/FileParameterValue.java b/core/src/main/java/hudson/model/FileParameterValue.java index c3e508d941a3..c42fedd604ae 100644 --- a/core/src/main/java/hudson/model/FileParameterValue.java +++ b/core/src/main/java/hudson/model/FileParameterValue.java @@ -310,12 +310,10 @@ public static class CancelledQueueListener extends QueueListener { public void onLeft(Queue.LeftItem li) { if (li.isCancelled()) { List actions = li.getActions(ParametersAction.class); - actions.forEach(a -> { - a.getAllParameters().stream() - .filter(p -> p instanceof FileParameterValue) - .map(p -> (FileParameterValue) p) - .forEach(this::deleteTmpFile); - }); + actions.forEach(a -> a.getAllParameters().stream() + .filter(p -> p instanceof FileParameterValue) + .map(p -> (FileParameterValue) p) + .forEach(this::deleteTmpFile)); } } diff --git a/core/src/main/java/hudson/model/Fingerprint.java b/core/src/main/java/hudson/model/Fingerprint.java index df482e28e03c..2f0908881dfd 100644 --- a/core/src/main/java/hudson/model/Fingerprint.java +++ b/core/src/main/java/hudson/model/Fingerprint.java @@ -53,7 +53,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; @@ -361,15 +360,10 @@ private RangeSet(Range initial) { */ public Iterable listNumbers() { final List ranges = getRanges(); - return new Iterable<>() { + return () -> new Iterators.FlattenIterator<>(ranges) { @Override - public Iterator iterator() { - return new Iterators.FlattenIterator<>(ranges) { - @Override - protected Iterator expand(Range range) { - return Iterators.sequence(range.start, range.end).iterator(); - } - }; + protected Iterator expand(Range range) { + return Iterators.sequence(range.start, range.end).iterator(); } }; } @@ -379,15 +373,10 @@ protected Iterator expand(Range range) { */ public Iterable listNumbersReverse() { final List ranges = getRanges(); - return new Iterable<>() { + return () -> new Iterators.FlattenIterator<>(Iterators.reverse(ranges)) { @Override - public Iterator iterator() { - return new Iterators.FlattenIterator<>(Iterators.reverse(ranges)) { - @Override - protected Iterator expand(Range range) { - return Iterators.reverseSequence(range.start, range.end).iterator(); - } - }; + protected Iterator expand(Range range) { + return Iterators.reverseSequence(range.start, range.end).iterator(); } }; } @@ -638,7 +627,7 @@ public synchronized boolean isEmpty() { * If this range is empty, this method throws an exception. */ public synchronized int min() { - return ranges.get(0).start; + return ranges.getFirst().start; } /** @@ -647,7 +636,7 @@ public synchronized int min() { * If this range is empty, this method throws an exception. */ public synchronized int max() { - return ranges.get(ranges.size() - 1).end; + return ranges.getLast().end; } /** @@ -660,7 +649,7 @@ public synchronized int max() { public synchronized boolean isSmallerThan(int n) { if (ranges.isEmpty()) return true; - return ranges.get(ranges.size() - 1).isSmallerThan(n); + return ranges.getLast().isSmallerThan(n); } /** @@ -1207,13 +1196,10 @@ public int size() { */ public @NonNull Collection getSortedFacets() { List r = new ArrayList<>(getFacets()); - r.sort(new Comparator<>() { - @Override - public int compare(FingerprintFacet o1, FingerprintFacet o2) { - long a = o1.getTimestamp(); - long b = o2.getTimestamp(); - return Long.compare(a, b); - } + r.sort((o1, o2) -> { + long a = o1.getTimestamp(); + long b = o2.getTimestamp(); + return Long.compare(a, b); }); return r; } @@ -1470,8 +1456,7 @@ private static boolean canDiscoverItem(@NonNull final String fullName) { if (canDiscoverTheItem) { ItemGroup current = itemBySystemUser.getParent(); do { - if (current instanceof Item) { - final Item i = (Item) current; + if (current instanceof Item i) { current = i.getParent(); if (!i.hasPermission2(userAuth, Item.READ)) { canDiscoverTheItem = false; diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java index 278038db9b5b..a92931afbf0c 100644 --- a/core/src/main/java/hudson/model/Job.java +++ b/core/src/main/java/hudson/model/Job.java @@ -1096,7 +1096,7 @@ protected List getEstimatedDurationCandidates() { while (candidates.size() < 3) { if (fallbackCandidates.isEmpty()) break; - RunT run = fallbackCandidates.remove(0); + RunT run = fallbackCandidates.removeFirst(); candidates.add(run); } @@ -1272,7 +1272,7 @@ public BallColor getIconColor() { */ public HealthReport getBuildHealth() { List reports = getBuildHealthReports(); - return reports.isEmpty() ? new HealthReport() : reports.get(0); + return reports.isEmpty() ? new HealthReport() : reports.getFirst(); } @Exported(name = "healthReport") diff --git a/core/src/main/java/hudson/model/JobPropertyDescriptor.java b/core/src/main/java/hudson/model/JobPropertyDescriptor.java index eb9b990b7056..f44312022b39 100644 --- a/core/src/main/java/hudson/model/JobPropertyDescriptor.java +++ b/core/src/main/java/hudson/model/JobPropertyDescriptor.java @@ -102,8 +102,7 @@ public JobProperty newInstance(StaplerRequest req, JSONObject formData) throw */ public boolean isApplicable(Class jobType) { Type parameterization = Types.getBaseClass(clazz, JobProperty.class); - if (parameterization instanceof ParameterizedType) { - ParameterizedType pt = (ParameterizedType) parameterization; + if (parameterization instanceof ParameterizedType pt) { Class applicable = Types.erasure(Types.getTypeArgument(pt, 0)); return applicable.isAssignableFrom(jobType); } else { diff --git a/core/src/main/java/hudson/model/Label.java b/core/src/main/java/hudson/model/Label.java index ce131f43c003..a2b1e5969a0b 100644 --- a/core/src/main/java/hudson/model/Label.java +++ b/core/src/main/java/hudson/model/Label.java @@ -176,14 +176,11 @@ public String getSearchUrl() { * {@link LabelAtom}s. */ public final boolean matches(final Collection labels) { - return matches(new VariableResolver<>() { - @Override - public Boolean resolve(String name) { - for (LabelAtom a : labels) - if (a.getName().equals(name)) - return true; - return false; - } + return matches(name -> { + for (LabelAtom a : labels) + if (a.getName().equals(name)) + return true; + return false; }); } diff --git a/core/src/main/java/hudson/model/MultiStageTimeSeries.java b/core/src/main/java/hudson/model/MultiStageTimeSeries.java index 84963cde928f..49b5abeb101d 100644 --- a/core/src/main/java/hudson/model/MultiStageTimeSeries.java +++ b/core/src/main/java/hudson/model/MultiStageTimeSeries.java @@ -127,12 +127,12 @@ public void update(float f) { * Selects a {@link TimeSeries}. */ public TimeSeries pick(TimeScale timeScale) { - switch (timeScale) { - case HOUR: return hour; - case MIN: return min; - case SEC10: return sec10; - default: throw new AssertionError(); - } + return switch (timeScale) { + case HOUR -> hour; + case MIN -> min; + case SEC10 -> sec10; + default -> throw new AssertionError(); + }; } /** @@ -169,12 +169,12 @@ public enum TimeScale { * this {@link TimeScale}. */ public DateFormat createDateFormat() { - switch (this) { - case HOUR: return new SimpleDateFormat("MMM/dd HH"); - case MIN: return new SimpleDateFormat("E HH:mm"); - case SEC10: return new SimpleDateFormat("HH:mm:ss"); - default: throw new AssertionError(); - } + return switch (this) { + case HOUR -> new SimpleDateFormat("MMM/dd HH"); + case MIN -> new SimpleDateFormat("E HH:mm"); + case SEC10 -> new SimpleDateFormat("HH:mm:ss"); + default -> throw new AssertionError(); + }; } /** diff --git a/core/src/main/java/hudson/model/PasswordParameterDefinition.java b/core/src/main/java/hudson/model/PasswordParameterDefinition.java index 901f1ee66712..0db16068d937 100644 --- a/core/src/main/java/hudson/model/PasswordParameterDefinition.java +++ b/core/src/main/java/hudson/model/PasswordParameterDefinition.java @@ -66,8 +66,7 @@ public PasswordParameterDefinition(@NonNull String name, @CheckForNull Secret de @Override public ParameterDefinition copyWithDefaultValue(ParameterValue defaultValue) { - if (defaultValue instanceof PasswordParameterValue) { - PasswordParameterValue value = (PasswordParameterValue) defaultValue; + if (defaultValue instanceof PasswordParameterValue value) { return new PasswordParameterDefinition(getName(), Secret.toString(value.getValue()), getDescription()); } else { return this; diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index 832c3db5c65f..992cef9a3607 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -426,21 +426,17 @@ public void load() { if (o instanceof Task) { // backward compatibility schedule((Task) o, 0); - } else if (o instanceof Item) { - Item item = (Item) o; + } else if (o instanceof Item item) { if (item.task == null) { continue; // botched persistence. throw this one away } - if (item instanceof WaitingItem) { - item.enter(this); - } else if (item instanceof BlockedItem) { - item.enter(this); - } else if (item instanceof BuildableItem) { - item.enter(this); - } else { - throw new IllegalStateException("Unknown item type! " + item); + switch (item) { + case WaitingItem waitingItem -> item.enter(this); + case BlockedItem blockedItem -> item.enter(this); + case BuildableItem buildableItem -> item.enter(this); + default -> throw new IllegalStateException("Unknown item type! " + item); } } } @@ -673,7 +669,7 @@ public WaitingItem schedule(Task p, int quietPeriod, List actions) { // whether the new one should affect all existing ones or not is debatable. I for myself // thought this would only affect one, so the code was bit of surprise, but I'm keeping the current // behaviour. - return ScheduleResult.existing(duplicatesInQueue.get(0)); + return ScheduleResult.existing(duplicatesInQueue.getFirst()); } finally { updateSnapshot(); } } finally { lock.unlock(); } @@ -828,8 +824,7 @@ private static boolean hasReadPermission(Item t, boolean valueIfNotAccessControl } private static boolean hasReadPermission(Queue.Task t, boolean valueIfNotAccessControlled) { - if (t instanceof AccessControlled) { - AccessControlled taskAC = (AccessControlled) t; + if (t instanceof AccessControlled taskAC) { if (taskAC.hasPermission(hudson.model.Item.READ) || taskAC.hasPermission(Permission.READ)) { // TODO should be unnecessary given the 'implies' relationship return true; @@ -869,8 +864,7 @@ public StubItem[] getDiscoverableItems() { } private List filterDiscoverableItemListBasedOnPermissions(List r, Item t) { - if (t.task instanceof hudson.model.Item) { - hudson.model.Item taskAsItem = (hudson.model.Item) t.task; + if (t.task instanceof hudson.model.Item taskAsItem) { if (!taskAsItem.hasPermission(hudson.model.Item.READ) && taskAsItem.hasPermission(hudson.model.Item.DISCOVER)) { r.add(new StubItem(new StubTask(t.task))); @@ -2523,8 +2517,7 @@ public org.acegisecurity.Authentication authenticate() { @Restricted(DoNotUse.class) // only for Stapler export public Api getApi() throws AccessDeniedException { - if (task instanceof AccessControlled) { - AccessControlled ac = (AccessControlled) task; + if (task instanceof AccessControlled ac) { if (!ac.hasPermission(hudson.model.Item.DISCOVER)) { return null; // same as getItem(long) returning null (details are printed only in case of -Dstapler.trace=true) } else if (!ac.hasPermission(hudson.model.Item.READ)) { diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java index a96b4dc80a99..bf6dc4a01641 100644 --- a/core/src/main/java/hudson/model/Run.java +++ b/core/src/main/java/hudson/model/Run.java @@ -1929,10 +1929,9 @@ private StreamBuildListener createBuildListener(@NonNull RunExecution job, Outpu } // Project specific log filters - if (project instanceof BuildableItemWithBuildWrappers && build instanceof AbstractBuild) { - BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project; + if (project instanceof BuildableItemWithBuildWrappers biwbw && build instanceof AbstractBuild abstractBuild) { for (BuildWrapper bw : biwbw.getBuildWrappersList()) { - logger = bw.decorateLogger((AbstractBuild) build, logger); + logger = bw.decorateLogger(abstractBuild, logger); } } @@ -2520,13 +2519,10 @@ protected void submit(JSONObject json) throws IOException { /** * Sort by date. Newer ones first. */ - public static final Comparator ORDER_BY_DATE = new Comparator<>() { - @Override - public int compare(@NonNull Run lhs, @NonNull Run rhs) { - long lt = lhs.getTimeInMillis(); - long rt = rhs.getTimeInMillis(); - return Long.compare(rt, lt); - } + public static final Comparator ORDER_BY_DATE = (lhs, rhs) -> { + long lt = lhs.getTimeInMillis(); + long rt = rhs.getTimeInMillis(); + return Long.compare(rt, lt); }; /** diff --git a/core/src/main/java/hudson/model/RunParameterDefinition.java b/core/src/main/java/hudson/model/RunParameterDefinition.java index 487d895839dd..3abced82da29 100644 --- a/core/src/main/java/hudson/model/RunParameterDefinition.java +++ b/core/src/main/java/hudson/model/RunParameterDefinition.java @@ -96,8 +96,7 @@ private RunParameterDefinition(@NonNull String name, String projectName, String @Override public ParameterDefinition copyWithDefaultValue(ParameterValue defaultValue) { - if (defaultValue instanceof RunParameterValue) { - RunParameterValue value = (RunParameterValue) defaultValue; + if (defaultValue instanceof RunParameterValue value) { return new RunParameterDefinition(getName(), getProjectName(), value.getRunId(), getDescription(), getFilter()); } else { return this; @@ -129,16 +128,12 @@ public RunParameterFilter getFilter() { */ public RunList getBuilds() { // use getFilter() method so we dont have to worry about null filter value. - switch (getFilter()) { - case COMPLETED: - return getProject().getBuilds().overThresholdOnly(Result.ABORTED).completedOnly(); - case SUCCESSFUL: - return getProject().getBuilds().overThresholdOnly(Result.UNSTABLE).completedOnly(); - case STABLE: - return getProject().getBuilds().overThresholdOnly(Result.SUCCESS).completedOnly(); - default: - return getProject().getBuilds(); - } + return switch (getFilter()) { + case COMPLETED -> getProject().getBuilds().overThresholdOnly(Result.ABORTED).completedOnly(); + case SUCCESSFUL -> getProject().getBuilds().overThresholdOnly(Result.UNSTABLE).completedOnly(); + case STABLE -> getProject().getBuilds().overThresholdOnly(Result.SUCCESS).completedOnly(); + default -> getProject().getBuilds(); + }; } @Extension @Symbol({"run", "runParam"}) @@ -179,20 +174,12 @@ public ParameterValue getDefaultParameterValue() { } // use getFilter() so we dont have to worry about null filter value. - switch (getFilter()) { - case COMPLETED: - lastBuild = project.getLastCompletedBuild(); - break; - case SUCCESSFUL: - lastBuild = project.getLastSuccessfulBuild(); - break; - case STABLE: - lastBuild = project.getLastStableBuild(); - break; - default: - lastBuild = project.getLastBuild(); - break; - } + lastBuild = switch (getFilter()) { + case COMPLETED -> project.getLastCompletedBuild(); + case SUCCESSFUL -> project.getLastSuccessfulBuild(); + case STABLE -> project.getLastStableBuild(); + default -> project.getLastBuild(); + }; if (lastBuild != null) { return createValue(lastBuild.getExternalizableId()); diff --git a/core/src/main/java/hudson/model/StringParameterDefinition.java b/core/src/main/java/hudson/model/StringParameterDefinition.java index 160e1b1a9c0c..67764c66e334 100644 --- a/core/src/main/java/hudson/model/StringParameterDefinition.java +++ b/core/src/main/java/hudson/model/StringParameterDefinition.java @@ -74,8 +74,7 @@ public StringParameterDefinition(@NonNull String name, @CheckForNull String defa @Override public ParameterDefinition copyWithDefaultValue(ParameterValue defaultValue) { - if (defaultValue instanceof StringParameterValue) { - StringParameterValue value = (StringParameterValue) defaultValue; + if (defaultValue instanceof StringParameterValue value) { return new StringParameterDefinition(getName(), value.value, getDescription()); } else { return this; diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index cdfaa6915683..1b1b9f2a4a82 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -378,8 +378,7 @@ public InstallationJob getJob(Plugin plugin) { List jobList = getJobs(); Collections.reverse(jobList); for (UpdateCenterJob job : jobList) - if (job instanceof InstallationJob) { - InstallationJob ij = (InstallationJob) job; + if (job instanceof InstallationJob ij) { if (ij.plugin.name.equals(plugin.name) && ij.plugin.sourceId.equals(plugin.sourceId)) return ij; } @@ -535,8 +534,7 @@ public synchronized void persistInstallStatus() { boolean activeInstalls = false; for (UpdateCenterJob job : jobs) { - if (job instanceof InstallationJob) { - InstallationJob installationJob = (InstallationJob) job; + if (job instanceof InstallationJob installationJob) { if (!installationJob.status.isSuccess()) { activeInstalls = true; } @@ -571,10 +569,9 @@ public HttpResponse doInstallStatus(StaplerRequest2 request) { List jobCopy = getJobs(); for (UpdateCenterJob job : jobCopy) { - if (job instanceof InstallationJob) { + if (job instanceof InstallationJob installationJob) { UUID jobCorrelationId = job.getCorrelationId(); if (correlationId == null || (jobCorrelationId != null && correlationId.equals(jobCorrelationId.toString()))) { - InstallationJob installationJob = (InstallationJob) job; Map pluginInfo = new LinkedHashMap<>(); pluginInfo.put("name", installationJob.plugin.name); pluginInfo.put("version", installationJob.plugin.version); @@ -1715,21 +1712,18 @@ public void run() { connectionStates.put(ConnectionStatus.INTERNET, ConnectionStatus.CHECKING); statuses.add(Messages.UpdateCenter_Status_CheckingInternet()); // Run the internet check in parallel - internetCheck = updateService.submit(new Runnable() { - @Override - public void run() { - try { - config.checkConnection(ConnectionCheckJob.this, connectionCheckUrl); - } catch (Exception e) { - if (e.getMessage().contains("Connection timed out")) { - // Google can't be down, so this is probably a proxy issue - connectionStates.put(ConnectionStatus.INTERNET, ConnectionStatus.FAILED); - statuses.add(Messages.UpdateCenter_Status_ConnectionFailed(Functions.xmlEscape(connectionCheckUrl), Jenkins.get().getRootUrl())); - return; - } + internetCheck = updateService.submit(() -> { + try { + config.checkConnection(ConnectionCheckJob.this, connectionCheckUrl); + } catch (Exception e) { + if (e.getMessage().contains("Connection timed out")) { + // Google can't be down, so this is probably a proxy issue + connectionStates.put(ConnectionStatus.INTERNET, ConnectionStatus.FAILED); + statuses.add(Messages.UpdateCenter_Status_ConnectionFailed(Functions.xmlEscape(connectionCheckUrl), Jenkins.get().getRootUrl())); + return; } - connectionStates.put(ConnectionStatus.INTERNET, ConnectionStatus.OK); } + connectionStates.put(ConnectionStatus.INTERNET, ConnectionStatus.OK); }); } else { LOGGER.log(WARNING, "Update site ''{0}'' does not declare the connection check URL. " @@ -2486,8 +2480,7 @@ protected boolean wasInstalled() { // we need it to continue installing return false; } - if (job instanceof InstallationJob) { - InstallationJob ij = (InstallationJob) job; + if (job instanceof InstallationJob ij) { if (ij.plugin.equals(plugin) && ij.plugin.version.equals(plugin.version)) { // wait until other install is completed synchronized (ij) { diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index fbd6668f46f6..bab68d16be80 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -67,7 +67,6 @@ import java.util.Set; import java.util.TreeMap; import java.util.UUID; -import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.function.Predicate; import java.util.logging.Level; @@ -194,11 +193,7 @@ public long getDataTimestamp() { @Deprecated public @CheckForNull Future updateDirectly(final boolean signatureCheck) { if (! getDataFile().exists() || isDue()) { - return Jenkins.get().getUpdateCenter().updateService.submit(new Callable<>() { - @Override public FormValidation call() throws Exception { - return updateDirectlyNow(signatureCheck); - } - }); + return Jenkins.get().getUpdateCenter().updateService.submit(() -> updateDirectlyNow(signatureCheck)); } else { return null; } @@ -1070,9 +1065,7 @@ public Warning(JSONObject o) { @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof Warning)) return false; - - Warning warning = (Warning) o; + if (!(o instanceof Warning warning)) return false; return id.equals(warning.id); } @@ -1200,8 +1193,7 @@ public IssueTracker(@NonNull String type, @NonNull String viewUrl, @CheckForNull } private static IssueTracker createFromJSONObject(Object o) { - if (o instanceof JSONObject) { - JSONObject jsonObject = (JSONObject) o; + if (o instanceof JSONObject jsonObject) { if (jsonObject.has("type") && jsonObject.has("viewUrl") && jsonObject.has("reportUrl")) { return new IssueTracker(jsonObject.getString("type"), jsonObject.getString("viewUrl"), jsonObject.getString("reportUrl")); } diff --git a/core/src/main/java/hudson/model/ViewDescriptor.java b/core/src/main/java/hudson/model/ViewDescriptor.java index e140ac474054..d0b5a08d1cc6 100644 --- a/core/src/main/java/hudson/model/ViewDescriptor.java +++ b/core/src/main/java/hudson/model/ViewDescriptor.java @@ -88,8 +88,7 @@ protected ViewDescriptor() { @Restricted(DoNotUse.class) public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value, @AncestorInPath ItemGroup container) { AutoCompletionCandidates candidates = AutoCompletionCandidates.ofJobNames(TopLevelItem.class, value, container); - if (container instanceof DirectlyModifiableTopLevelItemGroup) { - DirectlyModifiableTopLevelItemGroup modifiableContainer = (DirectlyModifiableTopLevelItemGroup) container; + if (container instanceof DirectlyModifiableTopLevelItemGroup modifiableContainer) { Iterator it = candidates.getValues().iterator(); while (it.hasNext()) { TopLevelItem item = Jenkins.get().getItem(it.next(), container, TopLevelItem.class); diff --git a/core/src/main/java/hudson/model/ViewGroupMixIn.java b/core/src/main/java/hudson/model/ViewGroupMixIn.java index 049475807152..a4492daa3431 100644 --- a/core/src/main/java/hudson/model/ViewGroupMixIn.java +++ b/core/src/main/java/hudson/model/ViewGroupMixIn.java @@ -171,7 +171,7 @@ public Collection getViews() { public View getPrimaryView() { View v = getView(primaryView()); if (v == null && !views().isEmpty()) // fallback - v = views().get(0); + v = views().getFirst(); return v; } diff --git a/core/src/main/java/hudson/model/WorkspaceCleanupThread.java b/core/src/main/java/hudson/model/WorkspaceCleanupThread.java index 8159f1f20cc1..4f5cde4dc9a1 100644 --- a/core/src/main/java/hudson/model/WorkspaceCleanupThread.java +++ b/core/src/main/java/hudson/model/WorkspaceCleanupThread.java @@ -112,8 +112,7 @@ private boolean shouldBeDeleted(@NonNull TopLevelItem item, FilePath dir, @NonNu // TODO could also be good to add checkbox that lets users configure a workspace to never be auto-cleaned. // TODO check instead for SCMTriggerItem: - if (item instanceof AbstractProject) { - AbstractProject p = (AbstractProject) item; + if (item instanceof AbstractProject p) { Node lb = p.getLastBuiltOn(); LOGGER.log(Level.FINER, "Directory {0} is last built on {1}", new Object[] {dir, lb}); if (lb != null && lb.equals(n)) { @@ -129,8 +128,7 @@ private boolean shouldBeDeleted(@NonNull TopLevelItem item, FilePath dir, @NonNu } // TODO this may only check the last build in fact: - if (item instanceof Job) { - Job j = (Job) item; + if (item instanceof Job j) { if (j.isBuilding()) { LOGGER.log(Level.FINE, "Job {0} is building, so not deleting", item.getFullDisplayName()); return false; diff --git a/core/src/main/java/hudson/model/queue/MappingWorksheet.java b/core/src/main/java/hudson/model/queue/MappingWorksheet.java index 902aa1c6da50..f15673f4209a 100644 --- a/core/src/main/java/hudson/model/queue/MappingWorksheet.java +++ b/core/src/main/java/hudson/model/queue/MappingWorksheet.java @@ -128,7 +128,7 @@ private ExecutorChunk(List base, int index) { super(base); this.index = index; assert !base.isEmpty(); - computer = base.get(0).getExecutor().getOwner(); + computer = base.getFirst().getExecutor().getOwner(); node = computer.getNode(); nodeAcl = node.getACL(); } @@ -206,10 +206,10 @@ private WorkChunk(List base, int index) { super(base); assert !base.isEmpty(); this.index = index; - this.assignedLabel = getAssignedLabel(base.get(0)); + this.assignedLabel = getAssignedLabel(base.getFirst()); @SuppressWarnings("deprecation") - Node lbo = base.get(0).getLastBuiltOn(); + Node lbo = base.getFirst().getLastBuiltOn(); for (ExecutorChunk ec : executors) { if (ec.node == lbo) { lastBuiltOn = ec; diff --git a/core/src/main/java/hudson/model/queue/QueueSorter.java b/core/src/main/java/hudson/model/queue/QueueSorter.java index 939d1c6fdff5..3f3eadb05e6f 100644 --- a/core/src/main/java/hudson/model/queue/QueueSorter.java +++ b/core/src/main/java/hudson/model/queue/QueueSorter.java @@ -70,7 +70,7 @@ public static void installDefaultQueueSorter() { Queue q = Jenkins.get().getQueue(); if (q.getSorter() != null) return; // someone has already installed something. leave that alone. - q.setSorter(all.get(0)); + q.setSorter(all.getFirst()); if (all.size() > 1) LOGGER.warning("Multiple QueueSorters are registered. Only the first one is used and the rest are ignored: " + all); } diff --git a/core/src/main/java/hudson/model/queue/WorkUnitContext.java b/core/src/main/java/hudson/model/queue/WorkUnitContext.java index 83320ab5d4f9..8526cf159bb2 100644 --- a/core/src/main/java/hudson/model/queue/WorkUnitContext.java +++ b/core/src/main/java/hudson/model/queue/WorkUnitContext.java @@ -118,7 +118,7 @@ public List getWorkUnits() { } public WorkUnit getPrimaryWorkUnit() { - return workUnits.get(0); + return workUnits.getFirst(); } /** diff --git a/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java b/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java index 0e2659b71f57..96aa62fa301a 100644 --- a/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java +++ b/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java @@ -21,29 +21,23 @@ @Extension public class NodeMonitorUpdater extends ComputerListener { - private static final Runnable MONITOR_UPDATER = new Runnable() { - @Override - public void run() { - for (NodeMonitor nm : ComputerSet.getMonitors()) { - nm.triggerUpdate(); - } + private static final Runnable MONITOR_UPDATER = () -> { + for (NodeMonitor nm : ComputerSet.getMonitors()) { + nm.triggerUpdate(); } }; - private static final Runnable MARKEDOFFLINE_UPDATER = new Runnable() { - @Override - public void run() { - MonitorMarkedNodeOffline no = AdministrativeMonitor.all().get(MonitorMarkedNodeOffline.class); - if (no != null) { - boolean markedOffline = false; - for (Computer c : Jenkins.get().getComputers()) { - if (c.getChannel() != null && c.getOfflineCause() instanceof MonitorOfflineCause) { - markedOffline = true; - break; - } + private static final Runnable MARKEDOFFLINE_UPDATER = () -> { + MonitorMarkedNodeOffline no = AdministrativeMonitor.all().get(MonitorMarkedNodeOffline.class); + if (no != null) { + boolean markedOffline = false; + for (Computer c : Jenkins.get().getComputers()) { + if (c.getChannel() != null && c.getOfflineCause() instanceof MonitorOfflineCause) { + markedOffline = true; + break; } - no.active = markedOffline; } + no.active = markedOffline; } }; diff --git a/core/src/main/java/hudson/scm/SCM.java b/core/src/main/java/hudson/scm/SCM.java index 4aafea498902..a20e8d4abe13 100644 --- a/core/src/main/java/hudson/scm/SCM.java +++ b/core/src/main/java/hudson/scm/SCM.java @@ -782,8 +782,7 @@ public static List> _for(@CheckForNull final Job project) { for (SCMDescriptor scmDescriptor : all()) { if (!scmDescriptor.isApplicable(project)) continue; - if (pd instanceof TopLevelItemDescriptor) { - TopLevelItemDescriptor apd = (TopLevelItemDescriptor) pd; + if (pd instanceof TopLevelItemDescriptor apd) { if (!apd.isApplicable(scmDescriptor)) continue; } diff --git a/core/src/main/java/hudson/search/Search.java b/core/src/main/java/hudson/search/Search.java index 25b615993f2d..92939e727239 100644 --- a/core/src/main/java/hudson/search/Search.java +++ b/core/src/main/java/hudson/search/Search.java @@ -115,8 +115,7 @@ private void doIndexImpl(StaplerRequest2 req, StaplerResponse2 rsp) throws IOExc List l = req.getAncestors(); for (int i = l.size() - 1; i >= 0; i--) { Ancestor a = l.get(i); - if (a.getObject() instanceof SearchableModelObject) { - SearchableModelObject smo = (SearchableModelObject) a.getObject(); + if (a.getObject() instanceof SearchableModelObject smo) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(String.format("smo.displayName=%s, searchName=%s", smo.getDisplayName(), smo.getSearchName())); } @@ -263,8 +262,7 @@ public int getMaxSearchSize() { private SearchIndex makeSuggestIndex(StaplerRequest2 req) { SearchIndexBuilder builder = new SearchIndexBuilder(); for (Ancestor a : req.getAncestors()) { - if (a.getObject() instanceof SearchableModelObject) { - SearchableModelObject smo = (SearchableModelObject) a.getObject(); + if (a.getObject() instanceof SearchableModelObject smo) { builder.add(smo.getSearchIndex()); } } @@ -377,7 +375,7 @@ static SuggestedItem findClosestSuggestedItem(List r, String quer // couldn't find an item with the query in the url so just // return the first one - return r.get(0); + return r.getFirst(); } /** @@ -399,7 +397,7 @@ public static SuggestedItem find(SearchIndex index, String query, SearchableMode return null; } else if (1 == r.size()) { - return r.get(0); + return r.getFirst(); } else { // we have more than one suggested item, so return the item who's url diff --git a/core/src/main/java/hudson/search/SuggestedItem.java b/core/src/main/java/hudson/search/SuggestedItem.java index 6911d002fe50..4a2b97480858 100644 --- a/core/src/main/java/hudson/search/SuggestedItem.java +++ b/core/src/main/java/hudson/search/SuggestedItem.java @@ -82,8 +82,7 @@ public String getUrl() { private static SuggestedItem build(SearchableModelObject searchContext, Item top) { ItemGroup parent = top.getParent(); - if (parent instanceof Item) { - Item parentItem = (Item) parent; + if (parent instanceof Item parentItem) { return new SuggestedItem(build(searchContext, parentItem), top); } return new SuggestedItem(top); diff --git a/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java b/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java index 3fd2dc2b0865..429c458f9119 100644 --- a/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java +++ b/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java @@ -64,6 +64,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.logging.Level; @@ -510,11 +511,7 @@ private User createAccount(SignupInfo si) throws IOException { } private boolean containsOnlyAcceptableCharacters(@NonNull String value) { - if (ID_REGEX == null) { - return value.matches(DEFAULT_ID_REGEX); - } else { - return value.matches(ID_REGEX); - } + return value.matches(Objects.requireNonNullElse(ID_REGEX, DEFAULT_ID_REGEX)); } @Restricted(NoExternalUse.class) // _entryForm.jelly and signup.jelly diff --git a/core/src/main/java/hudson/security/SecurityRealm.java b/core/src/main/java/hudson/security/SecurityRealm.java index 41b16e171de9..1bda207fbaf4 100644 --- a/core/src/main/java/hudson/security/SecurityRealm.java +++ b/core/src/main/java/hudson/security/SecurityRealm.java @@ -757,16 +757,8 @@ public static String getFrom() { private static class None extends SecurityRealm { @Override public SecurityComponents createSecurityComponents() { - return new SecurityComponents(new AuthenticationManager() { - @Override - public Authentication authenticate(Authentication authentication) { - return authentication; - } - }, new UserDetailsService() { - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - throw new UsernameNotFoundException(username); - } + return new SecurityComponents((AuthenticationManager) authentication -> authentication, username -> { + throw new UsernameNotFoundException(username); }); } diff --git a/core/src/main/java/hudson/security/UnwrapSecurityExceptionFilter.java b/core/src/main/java/hudson/security/UnwrapSecurityExceptionFilter.java index 683725b2fe0d..ec703788e4a2 100644 --- a/core/src/main/java/hudson/security/UnwrapSecurityExceptionFilter.java +++ b/core/src/main/java/hudson/security/UnwrapSecurityExceptionFilter.java @@ -61,8 +61,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha t = t.getCause(); } } - if (t instanceof JellyTagException) { - JellyTagException jte = (JellyTagException) t; + if (t instanceof JellyTagException jte) { Throwable cause = jte.getCause(); if (cause instanceof AccessDeniedException || cause instanceof AuthenticationException) { throw new ServletException(cause); diff --git a/core/src/main/java/hudson/security/csrf/CrumbFilter.java b/core/src/main/java/hudson/security/csrf/CrumbFilter.java index 6835a4365a3c..d061fff278ec 100644 --- a/core/src/main/java/hudson/security/csrf/CrumbFilter.java +++ b/core/src/main/java/hudson/security/csrf/CrumbFilter.java @@ -114,12 +114,11 @@ private static String canonicalPath(String path) { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CrumbIssuer crumbIssuer = getCrumbIssuer(); - if (crumbIssuer == null || !(request instanceof HttpServletRequest)) { + if (crumbIssuer == null || !(request instanceof HttpServletRequest httpRequest)) { chain.doFilter(request, response); return; } - HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if ("POST".equals(httpRequest.getMethod())) { diff --git a/core/src/main/java/hudson/security/csrf/CrumbIssuer.java b/core/src/main/java/hudson/security/csrf/CrumbIssuer.java index 491ec735b591..bb08bbc3c630 100644 --- a/core/src/main/java/hudson/security/csrf/CrumbIssuer.java +++ b/core/src/main/java/hudson/security/csrf/CrumbIssuer.java @@ -275,20 +275,21 @@ public static class RestrictedApi extends Api { setHeaders(rsp); String text; CrumbIssuer ci = (CrumbIssuer) bean; - if ("/*/crumbRequestField/text()".equals(xpath)) { // old FullDuplexHttpStream - text = ci.getCrumbRequestField(); - } else if ("/*/crumb/text()".equals(xpath)) { // ditto - text = ci.getCrumb(); - } else if ("concat(//crumbRequestField,\":\",//crumb)".equals(xpath)) { // new FullDuplexHttpStream; Main - text = ci.getCrumbRequestField() + ':' + ci.getCrumb(); - } else if ("concat(//crumbRequestField,'=',//crumb)".equals(xpath)) { // NetBeans - if (ci.getCrumbRequestField().startsWith(".") || ci.getCrumbRequestField().contains("-")) { - text = ci.getCrumbRequestField() + '=' + ci.getCrumb(); - } else { - text = null; + switch (xpath) { + case "/*/crumbRequestField/text()" -> // old FullDuplexHttpStream + text = ci.getCrumbRequestField(); + case "/*/crumb/text()" -> // ditto + text = ci.getCrumb(); + case "concat(//crumbRequestField,\":\",//crumb)" -> // new FullDuplexHttpStream; Main + text = ci.getCrumbRequestField() + ':' + ci.getCrumb(); + case "concat(//crumbRequestField,'=',//crumb)" -> { // NetBeans + if (ci.getCrumbRequestField().startsWith(".") || ci.getCrumbRequestField().contains("-")) { + text = ci.getCrumbRequestField() + '=' + ci.getCrumb(); + } else { + text = null; + } } - } else { - text = null; + case null, default -> text = null; } if (text != null) { try (OutputStream o = rsp.getOutputStream()) { diff --git a/core/src/main/java/hudson/security/csrf/DefaultCrumbIssuer.java b/core/src/main/java/hudson/security/csrf/DefaultCrumbIssuer.java index 8ef62867971f..119cca2f0f5d 100644 --- a/core/src/main/java/hudson/security/csrf/DefaultCrumbIssuer.java +++ b/core/src/main/java/hudson/security/csrf/DefaultCrumbIssuer.java @@ -101,9 +101,8 @@ private synchronized void initializeMessageDigest() { @Override @SuppressFBWarnings(value = "NM_WRONG_PACKAGE", justification = "false positive") protected synchronized String issueCrumb(ServletRequest request, String salt) { - if (request instanceof HttpServletRequest) { + if (request instanceof HttpServletRequest req) { if (md != null) { - HttpServletRequest req = (HttpServletRequest) request; StringBuilder buffer = new StringBuilder(); Authentication a = Jenkins.getAuthentication2(); buffer.append(a.getName()); diff --git a/core/src/main/java/hudson/slaves/ConnectionActivityMonitor.java b/core/src/main/java/hudson/slaves/ConnectionActivityMonitor.java index 0d3d1dcc536e..07dcdafbd825 100644 --- a/core/src/main/java/hudson/slaves/ConnectionActivityMonitor.java +++ b/core/src/main/java/hudson/slaves/ConnectionActivityMonitor.java @@ -61,8 +61,7 @@ protected void execute(TaskListener listener) throws IOException, InterruptedExc long now = System.currentTimeMillis(); for (Computer c : Jenkins.get().getComputers()) { VirtualChannel ch = c.getChannel(); - if (ch instanceof Channel) { - Channel channel = (Channel) ch; + if (ch instanceof Channel channel) { if (now - channel.getLastHeard() > TIME_TILL_PING) { // haven't heard from this agent for a while. Long lastPing = (Long) channel.getProperty(ConnectionActivityMonitor.class); diff --git a/core/src/main/java/hudson/slaves/SimpleScheduledRetentionStrategy.java b/core/src/main/java/hudson/slaves/SimpleScheduledRetentionStrategy.java index 81e5c9d0f236..70984480e16e 100644 --- a/core/src/main/java/hudson/slaves/SimpleScheduledRetentionStrategy.java +++ b/core/src/main/java/hudson/slaves/SimpleScheduledRetentionStrategy.java @@ -184,21 +184,18 @@ public synchronized long check(final SlaveComputer c) { LOGGER.log(INFO, "Trying to launch computer {0} as schedule says it should be on-line at " + "this point in time", new Object[]{c.getName()}); if (c.isLaunchSupported()) { - Computer.threadPoolForRemoting.submit(new Runnable() { - @Override - public void run() { - try { - c.connect(true).get(); - if (c.isOnline()) { - LOGGER.log(INFO, "Launched computer {0} per schedule", new Object[]{c.getName()}); - } - if (keepUpWhenActive && c.isOnline() && !c.isAcceptingTasks()) { - LOGGER.log(INFO, - "Enabling new jobs for computer {0} as it has started its scheduled uptime", - new Object[]{c.getName()}); - } - } catch (InterruptedException | ExecutionException e) { + Computer.threadPoolForRemoting.submit(() -> { + try { + c.connect(true).get(); + if (c.isOnline()) { + LOGGER.log(INFO, "Launched computer {0} per schedule", new Object[]{c.getName()}); + } + if (keepUpWhenActive && c.isOnline() && !c.isAcceptingTasks()) { + LOGGER.log(INFO, + "Enabling new jobs for computer {0} as it has started its scheduled uptime", + new Object[]{c.getName()}); } + } catch (InterruptedException | ExecutionException e) { } }); } diff --git a/core/src/main/java/hudson/slaves/SlaveComputer.java b/core/src/main/java/hudson/slaves/SlaveComputer.java index ca0f45b2ea93..a568317a8316 100644 --- a/core/src/main/java/hudson/slaves/SlaveComputer.java +++ b/core/src/main/java/hudson/slaves/SlaveComputer.java @@ -818,15 +818,12 @@ public HttpResponse doDoDisconnect(@QueryParameter String offlineMessage) { @Override public Future disconnect(OfflineCause cause) { super.disconnect(cause); - return Computer.threadPoolForRemoting.submit(new Runnable() { - @Override - public void run() { - // do this on another thread so that any lengthy disconnect operation - // (which could be typical) won't block UI thread. - launcher.beforeDisconnect(SlaveComputer.this, taskListener); - closeChannel(); - launcher.afterDisconnect(SlaveComputer.this, taskListener); - } + return Computer.threadPoolForRemoting.submit(() -> { + // do this on another thread so that any lengthy disconnect operation + // (which could be typical) won't block UI thread. + launcher.beforeDisconnect(SlaveComputer.this, taskListener); + closeChannel(); + launcher.afterDisconnect(SlaveComputer.this, taskListener); }); } diff --git a/core/src/main/java/hudson/tasks/ArtifactArchiver.java b/core/src/main/java/hudson/tasks/ArtifactArchiver.java index 0ee50010e6a2..93348a664ab6 100644 --- a/core/src/main/java/hudson/tasks/ArtifactArchiver.java +++ b/core/src/main/java/hudson/tasks/ArtifactArchiver.java @@ -386,8 +386,7 @@ public boolean isApplicable(Class jobType) { if (aa != null && aa.latestOnly != null) { if (aa.latestOnly) { BuildDiscarder bd = p.getBuildDiscarder(); - if (bd instanceof LogRotator) { - LogRotator lr = (LogRotator) bd; + if (bd instanceof LogRotator lr) { if (lr.getArtifactNumToKeep() == -1) { LogRotator newLr = new LogRotator(lr.getDaysToKeep(), lr.getNumToKeep(), lr.getArtifactDaysToKeep(), 1); newLr.setRemoveLastBuild(lr.isRemoveLastBuild()); diff --git a/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java b/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java index e71e244a11f0..c8030920618b 100644 --- a/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java +++ b/core/src/main/java/hudson/tasks/BuildStepCompatibilityLayer.java @@ -69,9 +69,8 @@ public boolean prebuild(AbstractBuild build, BuildListener listener) { */ @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { - if (this instanceof SimpleBuildStep) { + if (this instanceof SimpleBuildStep step) { // delegate to the overloaded version defined in SimpleBuildStep - final SimpleBuildStep step = (SimpleBuildStep) this; final FilePath workspace = build.getWorkspace(); if (step.requiresWorkspace() && workspace == null) { throw new AbortException("no workspace for " + build); diff --git a/core/src/main/java/hudson/tasks/BuildStepDescriptor.java b/core/src/main/java/hudson/tasks/BuildStepDescriptor.java index 742152b7545d..1a475c7a9e5e 100644 --- a/core/src/main/java/hudson/tasks/BuildStepDescriptor.java +++ b/core/src/main/java/hudson/tasks/BuildStepDescriptor.java @@ -79,8 +79,7 @@ List> filter(List> base, Class bd = (BuildStepDescriptor) d; + if (d instanceof BuildStepDescriptor bd) { if (!bd.isApplicable(type)) continue; r.add(bd); } else { diff --git a/core/src/main/java/hudson/tasks/BuildTrigger.java b/core/src/main/java/hudson/tasks/BuildTrigger.java index af71ff83b147..e918735c70e6 100644 --- a/core/src/main/java/hudson/tasks/BuildTrigger.java +++ b/core/src/main/java/hudson/tasks/BuildTrigger.java @@ -56,7 +56,6 @@ import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.StringTokenizer; @@ -137,10 +136,7 @@ public String getChildProjectsValue() { } public Result getThreshold() { - if (threshold == null) - return Result.SUCCESS; - else - return threshold; + return Objects.requireNonNullElse(threshold, Result.SUCCESS); } /** @@ -278,12 +274,9 @@ public static boolean execute(AbstractBuild build, BuildListener listener) { List downstreamProjects = new ArrayList<>( graph.getDownstreamDependencies(build.getProject())); // Sort topologically - downstreamProjects.sort(new Comparator<>() { - @Override - public int compare(Dependency lhs, Dependency rhs) { - // Swapping lhs/rhs to get reverse sort: - return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject()); - } + downstreamProjects.sort((lhs, rhs) -> { + // Swapping lhs/rhs to get reverse sort: + return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject()); }); for (Dependency dep : downstreamProjects) { diff --git a/core/src/main/java/hudson/tasks/BuildWrappers.java b/core/src/main/java/hudson/tasks/BuildWrappers.java index 5769ef6a8ef2..f31c89270fcf 100644 --- a/core/src/main/java/hudson/tasks/BuildWrappers.java +++ b/core/src/main/java/hudson/tasks/BuildWrappers.java @@ -61,8 +61,7 @@ public static List> getFor(AbstractProject projec for (Descriptor w : BuildWrapper.all()) { if (pd instanceof AbstractProjectDescriptor && !((AbstractProjectDescriptor) pd).isApplicable(w)) continue; - if (w instanceof BuildWrapperDescriptor) { - BuildWrapperDescriptor bwd = (BuildWrapperDescriptor) w; + if (w instanceof BuildWrapperDescriptor bwd) { if (bwd.isApplicable(project)) result.add(bwd); } else { diff --git a/core/src/main/java/hudson/tasks/Shell.java b/core/src/main/java/hudson/tasks/Shell.java index 9cd070136b55..855c1a8f78fd 100644 --- a/core/src/main/java/hudson/tasks/Shell.java +++ b/core/src/main/java/hudson/tasks/Shell.java @@ -103,7 +103,7 @@ public String[] buildCommandLine(FilePath script) { if (end < 0) end = command.length(); List args = new ArrayList<>(Arrays.asList(Util.tokenize(command.substring(0, end).trim()))); args.add(script.getRemote()); - args.set(0, args.get(0).substring(2)); // trim off "#!" + args.set(0, args.getFirst().substring(2)); // trim off "#!" return args.toArray(new String[0]); } else return new String[] { getDescriptor().getShellOrDefault(script.getChannel()), "-xe", script.getRemote()}; diff --git a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java index 5d7f4c0c024f..a3b02a42d1c1 100644 --- a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java +++ b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java @@ -116,8 +116,8 @@ protected FilePath findPullUpDirectory(FilePath root) throws IOException, Interr // otherwise leave it as is. List children = root.list(); if (children.size() != 1) return null; - if (children.get(0).isDirectory()) - return children.get(0); + if (children.getFirst().isDirectory()) + return children.getFirst(); return null; } @@ -153,7 +153,7 @@ public JSONObject reduce(List jsonList) { * @return true if the schema is the default one (id, name, url), false otherwise */ private boolean isDefaultSchema(List jsonList) { - JSONObject jsonToolInstallerList = jsonList.get(0); + JSONObject jsonToolInstallerList = jsonList.getFirst(); ToolInstallerList toolInstallerList = (ToolInstallerList) JSONObject.toBean(jsonToolInstallerList, ToolInstallerList.class); if (toolInstallerList != null) { diff --git a/core/src/main/java/hudson/tools/ToolDescriptor.java b/core/src/main/java/hudson/tools/ToolDescriptor.java index e20eb353af63..b287fb567dda 100644 --- a/core/src/main/java/hudson/tools/ToolDescriptor.java +++ b/core/src/main/java/hudson/tools/ToolDescriptor.java @@ -77,8 +77,7 @@ public T[] getInstallations() { return installations.clone(); Type bt = Types.getBaseClass(getClass(), ToolDescriptor.class); - if (bt instanceof ParameterizedType) { - ParameterizedType pt = (ParameterizedType) bt; + if (bt instanceof ParameterizedType pt) { // this 't' is the closest approximation of T of Descriptor. Class t = Types.erasure(pt.getActualTypeArguments()[0]); return (T[]) Array.newInstance(t, 0); diff --git a/core/src/main/java/hudson/tools/ToolInstallation.java b/core/src/main/java/hudson/tools/ToolInstallation.java index 87105bf17856..ba1b4632be1d 100644 --- a/core/src/main/java/hudson/tools/ToolInstallation.java +++ b/core/src/main/java/hudson/tools/ToolInstallation.java @@ -182,12 +182,10 @@ public synchronized DescribableList, ToolPropertyDescriptor> get */ public ToolInstallation translate(@NonNull Node node, EnvVars envs, TaskListener listener) throws IOException, InterruptedException { ToolInstallation t = this; - if (t instanceof NodeSpecific) { - NodeSpecific n = (NodeSpecific) t; + if (t instanceof NodeSpecific n) { t = (ToolInstallation) n.forNode(node, listener); } - if (t instanceof EnvironmentSpecific) { - EnvironmentSpecific e = (EnvironmentSpecific) t; + if (t instanceof EnvironmentSpecific e) { t = (ToolInstallation) e.forEnvironment(envs); } return t; diff --git a/core/src/main/java/hudson/triggers/SlowTriggerAdminMonitor.java b/core/src/main/java/hudson/triggers/SlowTriggerAdminMonitor.java index 67f7da93151c..dd90290c3f28 100644 --- a/core/src/main/java/hudson/triggers/SlowTriggerAdminMonitor.java +++ b/core/src/main/java/hudson/triggers/SlowTriggerAdminMonitor.java @@ -36,7 +36,7 @@ public class SlowTriggerAdminMonitor extends AdministrativeMonitor { @NonNull public static SlowTriggerAdminMonitor getInstance() { - return ExtensionList.lookup(SlowTriggerAdminMonitor.class).get(0); + return ExtensionList.lookup(SlowTriggerAdminMonitor.class).getFirst(); } public SlowTriggerAdminMonitor() { diff --git a/core/src/main/java/hudson/triggers/Trigger.java b/core/src/main/java/hudson/triggers/Trigger.java index 700878123946..03bb34e4ed22 100644 --- a/core/src/main/java/hudson/triggers/Trigger.java +++ b/core/src/main/java/hudson/triggers/Trigger.java @@ -29,7 +29,6 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.DependencyRunner; -import hudson.DependencyRunner.ProjectRunnable; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.ExtensionPoint; @@ -267,18 +266,15 @@ public static void checkTriggers(final Calendar cal) { // ignored, only the global setting is honored. The polling job is submitted only if the previous job has // terminated. // FIXME allow to set a global crontab spec - previousSynchronousPolling = scmd.getExecutor().submit(new DependencyRunner(new ProjectRunnable() { - @Override - public void run(AbstractProject p) { - for (Trigger t : (Collection) p.getTriggers().values()) { - if (t instanceof SCMTrigger) { - if (t.job != null) { - LOGGER.fine("synchronously triggering SCMTrigger for project " + t.job.getName()); - } else { - LOGGER.fine("synchronously triggering SCMTrigger for unknown project"); - } - t.run(); + previousSynchronousPolling = scmd.getExecutor().submit(new DependencyRunner(p -> { + for (Trigger t : (Collection) p.getTriggers().values()) { + if (t instanceof SCMTrigger) { + if (t.job != null) { + LOGGER.fine("synchronously triggering SCMTrigger for project " + t.job.getName()); + } else { + LOGGER.fine("synchronously triggering SCMTrigger for unknown project"); } + t.run(); } } })); diff --git a/core/src/main/java/hudson/util/ArgumentListBuilder.java b/core/src/main/java/hudson/util/ArgumentListBuilder.java index 9b2c7bebb594..fad7e5f6d10f 100644 --- a/core/src/main/java/hudson/util/ArgumentListBuilder.java +++ b/core/src/main/java/hudson/util/ArgumentListBuilder.java @@ -247,16 +247,11 @@ public ArgumentListBuilder addKeyValuePairsFromPropertyString(String prefix, Str * @see JENKINS-10539 */ private static VariableResolver propertiesGeneratingResolver(final VariableResolver original) { - - return new VariableResolver<>() { - - @Override - public String resolve(String name) { - final String value = original.resolve(name); - if (value == null) return null; - // Substitute one backslash with two - return value.replaceAll("\\\\", "\\\\\\\\"); - } + return name -> { + final String value = original.resolve(name); + if (value == null) return null; + // Substitute one backslash with two + return value.replaceAll("\\\\", "\\\\\\\\"); }; } diff --git a/core/src/main/java/hudson/util/CharacterEncodingFilter.java b/core/src/main/java/hudson/util/CharacterEncodingFilter.java index 2e42c0d8098c..eab7696598f4 100644 --- a/core/src/main/java/hudson/util/CharacterEncodingFilter.java +++ b/core/src/main/java/hudson/util/CharacterEncodingFilter.java @@ -75,8 +75,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha throws IOException, ServletException { if (!DISABLE_FILTER) { - if (request instanceof HttpServletRequest) { - HttpServletRequest req = (HttpServletRequest) request; + if (request instanceof HttpServletRequest req) { if (shouldSetCharacterEncoding(req)) { req.setCharacterEncoding(ENCODING); } diff --git a/core/src/main/java/hudson/util/ChartUtil.java b/core/src/main/java/hudson/util/ChartUtil.java index 2880d01b76a8..801e451453ca 100644 --- a/core/src/main/java/hudson/util/ChartUtil.java +++ b/core/src/main/java/hudson/util/ChartUtil.java @@ -85,8 +85,7 @@ public int compareTo(NumberOnlyBuildLabel that) { @Override public boolean equals(Object o) { - if (!(o instanceof NumberOnlyBuildLabel)) return false; - NumberOnlyBuildLabel that = (NumberOnlyBuildLabel) o; + if (!(o instanceof NumberOnlyBuildLabel that)) return false; return run == that.run; } diff --git a/core/src/main/java/hudson/util/CompressedFile.java b/core/src/main/java/hudson/util/CompressedFile.java index cd08f838a250..143f05e54452 100644 --- a/core/src/main/java/hudson/util/CompressedFile.java +++ b/core/src/main/java/hudson/util/CompressedFile.java @@ -137,34 +137,31 @@ public String loadAsString() throws IOException { * the further reading will be done from the compressed stream. */ public void compress() { - compressionThread.submit(new Runnable() { - @Override - public void run() { - boolean success; - try (InputStream in = read(); - OutputStream os = Files.newOutputStream(gz.toPath()); - OutputStream out = new GZIPOutputStream(os)) { - org.apache.commons.io.IOUtils.copy(in, out); - out.flush(); - success = true; - } catch (IOException | InvalidPathException e) { - LOGGER.log(Level.WARNING, "Failed to compress " + file, e); - success = false; - } - - File fileToDelete; - if (success) { - // if the compressed file is created successfully, remove the original - fileToDelete = file; - } else { - // in case a processing is left in the middle - fileToDelete = gz; - } - try { - Files.deleteIfExists(fileToDelete.toPath()); - } catch (IOException | InvalidPathException e) { - LOGGER.log(Level.WARNING, "Failed to delete " + fileToDelete, e); - } + compressionThread.submit(() -> { + boolean success; + try (InputStream in = read(); + OutputStream os = Files.newOutputStream(gz.toPath()); + OutputStream out = new GZIPOutputStream(os)) { + org.apache.commons.io.IOUtils.copy(in, out); + out.flush(); + success = true; + } catch (IOException | InvalidPathException e) { + LOGGER.log(Level.WARNING, "Failed to compress " + file, e); + success = false; + } + + File fileToDelete; + if (success) { + // if the compressed file is created successfully, remove the original + fileToDelete = file; + } else { + // in case a processing is left in the middle + fileToDelete = gz; + } + try { + Files.deleteIfExists(fileToDelete.toPath()); + } catch (IOException | InvalidPathException e) { + LOGGER.log(Level.WARNING, "Failed to delete " + fileToDelete, e); } }); } diff --git a/core/src/main/java/hudson/util/DescribableList.java b/core/src/main/java/hudson/util/DescribableList.java index dbb499b4df66..f31ac373092b 100644 --- a/core/src/main/java/hudson/util/DescribableList.java +++ b/core/src/main/java/hudson/util/DescribableList.java @@ -315,16 +315,12 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co throw x; } catch (InvocationTargetException e) { Throwable t = e.getCause(); - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else if (t instanceof IOException) { - throw new UncheckedIOException((IOException) t); - } else if (t instanceof Exception) { - throw new RuntimeException(t); - } else if (t instanceof Error) { - throw (Error) t; - } else { - throw new Error(e); + switch (t) { + case RuntimeException runtimeException -> throw runtimeException; + case IOException ioException -> throw new UncheckedIOException(ioException); + case Exception exception -> throw new RuntimeException(t); + case Error error -> throw error; + case null, default -> throw new Error(e); } } } diff --git a/core/src/main/java/hudson/util/InterceptingProxy.java b/core/src/main/java/hudson/util/InterceptingProxy.java index 3ab7ebb0b318..1de286e193cb 100644 --- a/core/src/main/java/hudson/util/InterceptingProxy.java +++ b/core/src/main/java/hudson/util/InterceptingProxy.java @@ -1,6 +1,5 @@ package hudson.util; -import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -17,14 +16,11 @@ public abstract class InterceptingProxy { protected abstract Object call(Object o, Method m, Object[] args) throws Throwable; public final T wrap(Class type, final T object) { - return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - try { - return call(object, method, args); - } catch (InvocationTargetException e) { - throw e.getTargetException(); - } + return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, (proxy, method, args) -> { + try { + return call(object, method, args); + } catch (InvocationTargetException e) { + throw e.getTargetException(); } })); } diff --git a/core/src/main/java/hudson/util/PersistedList.java b/core/src/main/java/hudson/util/PersistedList.java index 5a93a69641c8..4e8ccdbf6d7a 100644 --- a/core/src/main/java/hudson/util/PersistedList.java +++ b/core/src/main/java/hudson/util/PersistedList.java @@ -304,16 +304,12 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co throw x; } catch (InvocationTargetException e) { Throwable t = e.getCause(); - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else if (t instanceof IOException) { - throw new UncheckedIOException((IOException) t); - } else if (t instanceof Exception) { - throw new RuntimeException(t); - } else if (t instanceof Error) { - throw (Error) t; - } else { - throw new Error(e); + switch (t) { + case RuntimeException runtimeException -> throw runtimeException; + case IOException ioException -> throw new UncheckedIOException(ioException); + case Exception exception -> throw new RuntimeException(t); + case Error error -> throw error; + case null, default -> throw new Error(e); } } } diff --git a/core/src/main/java/hudson/util/ProcessTree.java b/core/src/main/java/hudson/util/ProcessTree.java index 21e811a877fd..4a4e3d94e178 100644 --- a/core/src/main/java/hudson/util/ProcessTree.java +++ b/core/src/main/java/hudson/util/ProcessTree.java @@ -462,22 +462,19 @@ public static ProcessTree get() { return new Windows(vetoes); String os = Util.fixNull(System.getProperty("os.name")); - if (os.equals("Linux")) - return new Linux(vetoes); - if (os.equals("AIX")) - return new AIX(vetoes); - if (os.equals("SunOS")) - return new Solaris(vetoes); - if (os.equals("Mac OS X")) - return new Darwin(vetoes); - if (os.equals("FreeBSD")) - return new FreeBSD(vetoes); + return switch (os) { + case "Linux" -> new Linux(vetoes); + case "AIX" -> new AIX(vetoes); + case "SunOS" -> new Solaris(vetoes); + case "Mac OS X" -> new Darwin(vetoes); + case "FreeBSD" -> new FreeBSD(vetoes); + default -> DEFAULT; + }; } catch (LinkageError e) { LOGGER.log(Level.FINE, "Failed to load OS-specific implementation; reverting to the default", e); enabled = false; + return DEFAULT; } - - return DEFAULT; } private static class DoVetoersExist extends SlaveToMasterCallable { diff --git a/core/src/main/java/hudson/util/QueryParameterMap.java b/core/src/main/java/hudson/util/QueryParameterMap.java index fc846c6fc73b..226881f6eccc 100644 --- a/core/src/main/java/hudson/util/QueryParameterMap.java +++ b/core/src/main/java/hudson/util/QueryParameterMap.java @@ -80,7 +80,7 @@ public QueryParameterMap(javax.servlet.http.HttpServletRequest req) { public String get(String name) { List v = store.get(name); - return v != null ? v.get(0) : null; + return v != null ? v.getFirst() : null; } public List getAll(String name) { diff --git a/core/src/main/java/hudson/util/RobustReflectionConverter.java b/core/src/main/java/hudson/util/RobustReflectionConverter.java index 5267692252b9..af1a9f241112 100644 --- a/core/src/main/java/hudson/util/RobustReflectionConverter.java +++ b/core/src/main/java/hudson/util/RobustReflectionConverter.java @@ -200,27 +200,25 @@ private void stopVisiting() { } } + @SuppressWarnings("deprecation") protected void doMarshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) { final Set seenFields = new HashSet(); final Set seenAsAttributes = new HashSet(); // Attributes might be preferred to child elements ... - reflectionProvider.visitSerializableFields(source, new ReflectionProvider.Visitor() { - @SuppressWarnings("deprecation") // deliberately calling deprecated methods? - @Override - public void visit(String fieldName, Class type, Class definedIn, Object value) { - SingleValueConverter converter = mapper.getConverterFromItemType(fieldName, type, definedIn); - if (converter == null) converter = mapper.getConverterFromItemType(fieldName, type); - if (converter == null) converter = mapper.getConverterFromItemType(type); - if (converter != null) { - if (value != null) { - final String str = converter.toString(value); - if (str != null) { - writer.addAttribute(mapper.aliasForAttribute(fieldName), str); - } + // deliberately calling deprecated methods? + reflectionProvider.visitSerializableFields(source, (fieldName, type, definedIn, value) -> { + SingleValueConverter converter = mapper.getConverterFromItemType(fieldName, type, definedIn); + if (converter == null) converter = mapper.getConverterFromItemType(fieldName, type); + if (converter == null) converter = mapper.getConverterFromItemType(type); + if (converter != null) { + if (value != null) { + final String str = converter.toString(value); + if (str != null) { + writer.addAttribute(mapper.aliasForAttribute(fieldName), str); } - seenAsAttributes.add(fieldName); } + seenAsAttributes.add(fieldName); } }); diff --git a/core/src/main/java/hudson/util/RunList.java b/core/src/main/java/hudson/util/RunList.java index 9e3de481735d..8e090d7d2582 100644 --- a/core/src/main/java/hudson/util/RunList.java +++ b/core/src/main/java/hudson/util/RunList.java @@ -40,7 +40,6 @@ import java.util.Calendar; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Iterator; @@ -105,13 +104,10 @@ public static , R extends Run> RunList fromJobs(Ite } private static Iterable combine(Iterable> runLists) { - return Iterables.mergeSorted(runLists, new Comparator<>() { - @Override - public int compare(R o1, R o2) { - long lhs = o1.getTimeInMillis(); - long rhs = o2.getTimeInMillis(); - return Long.compare(rhs, lhs); - } + return Iterables.mergeSorted(runLists, (o1, o2) -> { + long lhs = o1.getTimeInMillis(); + long rhs = o2.getTimeInMillis(); + return Long.compare(rhs, lhs); }); } @@ -286,12 +282,7 @@ public String toString() { * @since 1.507 */ public RunList limit(final int n) { - return limit(new CountingPredicate<>() { - @Override - public boolean apply(int index, R input) { - return index < n; - } - }); + return limit((index, input) -> index < n); } /** @@ -344,12 +335,7 @@ public RunList regressionOnly() { */ public RunList byTimestamp(final long start, final long end) { return - limit(new CountingPredicate<>() { - @Override - public boolean apply(int index, R r) { - return start <= r.getTimeInMillis(); - } - }).filter((Predicate) r -> r.getTimeInMillis() < end); + limit((index, r) -> start <= r.getTimeInMillis()).filter((Predicate) r -> r.getTimeInMillis() < end); } /** @@ -366,11 +352,6 @@ public RunList newBuilds() { // can't publish on-going builds return filter((Predicate) r -> !r.isBuilding()) // put at least 10 builds, but otherwise ignore old builds - .limit(new CountingPredicate<>() { - @Override - public boolean apply(int index, R r) { - return index < 10 || r.getTimeInMillis() >= t; - } - }); + .limit((index, r) -> index < 10 || r.getTimeInMillis() >= t); } } diff --git a/core/src/main/java/hudson/util/jelly/MorphTagLibrary.java b/core/src/main/java/hudson/util/jelly/MorphTagLibrary.java index 785bb6ef5067..8c4e94141c73 100644 --- a/core/src/main/java/hudson/util/jelly/MorphTagLibrary.java +++ b/core/src/main/java/hudson/util/jelly/MorphTagLibrary.java @@ -61,13 +61,13 @@ private Object evalAttribute(String name, JellyContext context) { private Collection getExclusions(JellyContext context) { Object exclusion = evalAttribute(EXCEPT_ATTRIBUTES, context); - if (exclusion == null) - return Collections.emptySet(); - if (exclusion instanceof String) - return Arrays.asList(exclusion.toString().split("\\s+")); // split by whitespace - if (exclusion instanceof Collection) - return (Collection) exclusion; - throw new IllegalArgumentException("Expected collection for exclusion but found :" + exclusion); + return switch (exclusion) { + case null -> Collections.emptySet(); + case String s -> Arrays.asList(exclusion.toString().split("\\s+")); // split by whitespace + case Collection collection -> collection; + default -> + throw new IllegalArgumentException("Expected collection for exclusion but found :" + exclusion); + }; } @Override diff --git a/core/src/main/java/hudson/widgets/HistoryWidget.java b/core/src/main/java/hudson/widgets/HistoryWidget.java index f1f9c7791e88..5a067bd7c978 100644 --- a/core/src/main/java/hudson/widgets/HistoryWidget.java +++ b/core/src/main/java/hudson/widgets/HistoryWidget.java @@ -264,7 +264,7 @@ public void doAjax(StaplerRequest2 req, StaplerResponse2 rsp, nn = n; } else { // every record fetched this time is frozen. next fetch should start from the next build - nn = adapter.getNextKey(adapter.getKey(items.get(0))); + nn = adapter.getNextKey(adapter.getKey(items.getFirst())); } } diff --git a/core/src/main/java/jenkins/UserAgentURLConnectionDecorator.java b/core/src/main/java/jenkins/UserAgentURLConnectionDecorator.java index cab141b01fec..5f7fdc158c13 100644 --- a/core/src/main/java/jenkins/UserAgentURLConnectionDecorator.java +++ b/core/src/main/java/jenkins/UserAgentURLConnectionDecorator.java @@ -50,8 +50,7 @@ public class UserAgentURLConnectionDecorator extends URLConnectionDecorator { @Override public void decorate(URLConnection con) throws IOException { - if (!DISABLED && con instanceof HttpURLConnection) { - HttpURLConnection httpConnection = (HttpURLConnection) con; + if (!DISABLED && con instanceof HttpURLConnection httpConnection) { httpConnection.setRequestProperty("User-Agent", getUserAgent()); } } diff --git a/core/src/main/java/jenkins/YesNoMaybe.java b/core/src/main/java/jenkins/YesNoMaybe.java index 8e682818b2d7..bd3100c83c33 100644 --- a/core/src/main/java/jenkins/YesNoMaybe.java +++ b/core/src/main/java/jenkins/YesNoMaybe.java @@ -47,13 +47,10 @@ public static Boolean toBoolean(YesNoMaybe v) { @SuppressFBWarnings(value = "NP_BOOLEAN_RETURN_NULL", justification = "bridge method for backward compatibility") public Boolean toBool() { - switch (this) { - case YES: - return true; - case NO: - return false; - default: - return null; - } + return switch (this) { + case YES -> true; + case NO -> false; + default -> null; + }; } } diff --git a/core/src/main/java/jenkins/install/InstallUtil.java b/core/src/main/java/jenkins/install/InstallUtil.java index 6fb37e20bf3a..6f50468a119d 100644 --- a/core/src/main/java/jenkins/install/InstallUtil.java +++ b/core/src/main/java/jenkins/install/InstallUtil.java @@ -307,8 +307,7 @@ public static synchronized void persistInstallStatus(List insta LOGGER.fine("Writing install state to: " + installingPluginsFile.getAbsolutePath()); Map statuses = new HashMap<>(); for (UpdateCenterJob j : installingPlugins) { - if (j instanceof InstallationJob && j.getCorrelationId() != null) { // only include install jobs with a correlation id (directly selected) - InstallationJob ij = (InstallationJob) j; + if (j instanceof InstallationJob ij && j.getCorrelationId() != null) { // only include install jobs with a correlation id (directly selected) InstallationStatus status = ij.status; String statusText = status.getType(); if (status instanceof Installing) { // flag currently installing plugins as pending diff --git a/core/src/main/java/jenkins/install/SetupWizard.java b/core/src/main/java/jenkins/install/SetupWizard.java index 05830a00a6d1..14d4b9222fca 100644 --- a/core/src/main/java/jenkins/install/SetupWizard.java +++ b/core/src/main/java/jenkins/install/SetupWizard.java @@ -307,8 +307,7 @@ public boolean isUsingSecurityToken() { */ /*package*/ boolean isUsingSecurityDefaults() { Jenkins j = Jenkins.get(); - if (j.getSecurityRealm() instanceof HudsonPrivateSecurityRealm) { - HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm) j.getSecurityRealm(); + if (j.getSecurityRealm() instanceof HudsonPrivateSecurityRealm securityRealm) { try { if (securityRealm.getAllUsers().size() == 1) { HudsonPrivateSecurityRealm.Details details = securityRealm.load(SetupWizard.initialSetupAdminUserName); @@ -633,14 +632,12 @@ public JSONArray getPlatformPluginUpdates() { JSONArray pluginCategories = JSONArray.fromObject(getPlatformPluginList().toString()); for (Iterator categoryIterator = pluginCategories.iterator(); categoryIterator.hasNext();) { Object category = categoryIterator.next(); - if (category instanceof JSONObject) { - JSONObject cat = (JSONObject) category; + if (category instanceof JSONObject cat) { JSONArray plugins = cat.getJSONArray("plugins"); nextPlugin: for (Iterator pluginIterator = plugins.iterator(); pluginIterator.hasNext();) { Object pluginData = pluginIterator.next(); - if (pluginData instanceof JSONObject) { - JSONObject plugin = (JSONObject) pluginData; + if (pluginData instanceof JSONObject plugin) { if (plugin.has("added")) { String sinceVersion = plugin.getString("added"); if (sinceVersion != null) { @@ -764,8 +761,7 @@ public void init(FilterConfig cfg) throws ServletException { @SuppressFBWarnings(value = "UNVALIDATED_REDIRECT", justification = "TODO needs triage") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Force root requests to the setup wizard - if (request instanceof HttpServletRequest && !Jenkins.get().getInstallState().isSetupComplete()) { - HttpServletRequest req = (HttpServletRequest) request; + if (request instanceof HttpServletRequest req && !Jenkins.get().getInstallState().isSetupComplete()) { String requestURI = req.getRequestURI(); if (requestURI.equals(req.getContextPath()) && !requestURI.endsWith("/")) { ((HttpServletResponse) response).sendRedirect(req.getContextPath() + "/"); diff --git a/core/src/main/java/jenkins/model/CoreEnvironmentContributor.java b/core/src/main/java/jenkins/model/CoreEnvironmentContributor.java index 21fc9758984a..86d0eda4c452 100644 --- a/core/src/main/java/jenkins/model/CoreEnvironmentContributor.java +++ b/core/src/main/java/jenkins/model/CoreEnvironmentContributor.java @@ -55,8 +55,7 @@ public void buildEnvironmentFor(Job j, EnvVars env, TaskListener listener) throw env.put("HUDSON_HOME", root); // legacy compatibility Thread t = Thread.currentThread(); - if (t instanceof Executor) { - Executor e = (Executor) t; + if (t instanceof Executor e) { env.put("EXECUTOR_NUMBER", String.valueOf(e.getNumber())); if (e.getOwner() instanceof MasterComputer) { env.put("NODE_NAME", Jenkins.get().getSelfLabel().getName()); diff --git a/core/src/main/java/jenkins/model/Jenkins.java b/core/src/main/java/jenkins/model/Jenkins.java index 332c10386b06..c775e2bec982 100644 --- a/core/src/main/java/jenkins/model/Jenkins.java +++ b/core/src/main/java/jenkins/model/Jenkins.java @@ -305,7 +305,6 @@ import org.apache.commons.jelly.JellyException; import org.apache.commons.jelly.Script; import org.apache.commons.logging.LogFactory; -import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.Milestone; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.ReactorException; @@ -2120,7 +2119,7 @@ public JDK getJDK(String name) { if (name == null) { // if only one JDK is configured, "default JDK" should mean that JDK. List jdks = getJDKs(); - if (jdks.size() == 1) return jdks.get(0); + if (jdks.size() == 1) return jdks.getFirst(); return null; } for (JDK j : getJDKs()) { @@ -2871,7 +2870,7 @@ public void refreshExtensions() throws ExtensionRefreshException { // if we find a new ExtensionFinder, we need it to list up all the extension points as well List> newFinders = new ArrayList<>(delta.find(ExtensionFinder.class)); while (!newFinders.isEmpty()) { - ExtensionFinder f = newFinders.remove(newFinders.size() - 1).getInstance(); + ExtensionFinder f = newFinders.removeLast().getInstance(); LOGGER.finer(() -> "found new ExtensionFinder " + f); ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); @@ -3370,7 +3369,7 @@ public void load() throws IOException { if (views.isEmpty() || primaryView == null) { View v = new AllView(AllView.DEFAULT_VIEW_NAME); setViewOwner(v); - views.add(0, v); + views.addFirst(v); primaryView = v.getViewName(); } primaryView = AllView.migrateLegacyPrimaryAllViewLocalizedName(views, primaryView); @@ -3473,95 +3472,83 @@ private synchronized TaskBuilder loadTasks() throws IOException { final Set loadedNames = Collections.synchronizedSet(new HashSet<>()); TaskGraphBuilder g = new TaskGraphBuilder(); - Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(SYSTEM_CONFIG_LOADED).add("Loading global config", new Executable() { - @Override - public void run(Reactor session) throws Exception { - load(); - // if we are loading old data that doesn't have this field - if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) { - nodes.setNodes(slaves); - slaves = null; - } else { - nodes.load(); - } + Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(SYSTEM_CONFIG_LOADED).add("Loading global config", session -> { + load(); + // if we are loading old data that doesn't have this field + if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) { + nodes.setNodes(slaves); + slaves = null; + } else { + nodes.load(); } }); List loadJobs = new ArrayList<>(); for (final File subdir : subdirs) { - loadJobs.add(g.requires(loadJenkins).requires(SYSTEM_CONFIG_ADAPTED).attains(JOB_LOADED).notFatal().add("Loading item " + subdir.getName(), new Executable() { - @Override - public void run(Reactor session) throws Exception { - if (!Items.getConfigFile(subdir).exists()) { - //Does not have job config file, so it is not a jenkins job hence skip it - return; - } - TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); - items.put(item.getName(), item); - loadedNames.add(item.getName()); + loadJobs.add(g.requires(loadJenkins).requires(SYSTEM_CONFIG_ADAPTED).attains(JOB_LOADED).notFatal().add("Loading item " + subdir.getName(), session -> { + if (!Items.getConfigFile(subdir).exists()) { + //Does not have job config file, so it is not a jenkins job hence skip it + return; } + TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); + items.put(item.getName(), item); + loadedNames.add(item.getName()); })); } - g.requires(loadJobs.toArray(new Handle[0])).attains(JOB_LOADED).add("Cleaning up obsolete items deleted from the disk", new Executable() { - @Override - public void run(Reactor reactor) { - // anything we didn't load from disk, throw them away. - // doing this after loading from disk allows newly loaded items - // to inspect what already existed in memory (in case of reloading) - - // retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one - // hopefully there shouldn't be too many of them. - for (String name : items.keySet()) { - if (!loadedNames.contains(name)) - items.remove(name); - } + g.requires(loadJobs.toArray(new Handle[0])).attains(JOB_LOADED).add("Cleaning up obsolete items deleted from the disk", reactor -> { + // anything we didn't load from disk, throw them away. + // doing this after loading from disk allows newly loaded items + // to inspect what already existed in memory (in case of reloading) + + // retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one + // hopefully there shouldn't be too many of them. + for (String name : items.keySet()) { + if (!loadedNames.contains(name)) + items.remove(name); } }); - g.requires(JOB_CONFIG_ADAPTED).attains(COMPLETED).add("Finalizing set up", new Executable() { - @Override - public void run(Reactor session) throws Exception { - rebuildDependencyGraph(); - - { // recompute label objects - populates the labels mapping. - for (Node slave : nodes.getNodes()) - // Note that not all labels are visible until the agents have connected. - slave.getAssignedLabels(); - getAssignedLabels(); - } + g.requires(JOB_CONFIG_ADAPTED).attains(COMPLETED).add("Finalizing set up", session -> { + rebuildDependencyGraph(); - if (useSecurity != null && !useSecurity) { - // forced reset to the unsecure mode. - // this works as an escape hatch for people who locked themselves out. - authorizationStrategy = AuthorizationStrategy.UNSECURED; - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - } else { - // read in old data that doesn't have the security field set - if (authorizationStrategy == null) { - if (useSecurity == null) - authorizationStrategy = AuthorizationStrategy.UNSECURED; - else - authorizationStrategy = new LegacyAuthorizationStrategy(); - } - if (securityRealm == null) { - if (useSecurity == null) - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - else - setSecurityRealm(new LegacySecurityRealm()); - } + { // recompute label objects - populates the labels mapping. + for (Node slave : nodes.getNodes()) + // Note that not all labels are visible until the agents have connected. + slave.getAssignedLabels(); + getAssignedLabels(); + } + + if (useSecurity != null && !useSecurity) { + // forced reset to the unsecure mode. + // this works as an escape hatch for people who locked themselves out. + authorizationStrategy = AuthorizationStrategy.UNSECURED; + setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); + } else { + // read in old data that doesn't have the security field set + if (authorizationStrategy == null) { + if (useSecurity == null) + authorizationStrategy = AuthorizationStrategy.UNSECURED; + else + authorizationStrategy = new LegacyAuthorizationStrategy(); + } + if (securityRealm == null) { + if (useSecurity == null) + setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); + else + setSecurityRealm(new LegacySecurityRealm()); } + } - // Allow the disabling system property to interfere here - setCrumbIssuer(getCrumbIssuer()); + // Allow the disabling system property to interfere here + setCrumbIssuer(getCrumbIssuer()); - // auto register root actions - for (Action a : getExtensionList(RootAction.class)) - if (!actions.contains(a)) actions.add(a); + // auto register root actions + for (Action a : getExtensionList(RootAction.class)) + if (!actions.contains(a)) actions.add(a); - setupWizard = ExtensionList.lookupSingleton(SetupWizard.class); - getInstallState().initializeState(); - } + setupWizard = ExtensionList.lookupSingleton(SetupWizard.class); + getInstallState().initializeState(); }); return g; @@ -5104,17 +5091,11 @@ public static boolean isCheckURIEncodingEnabled() { public Future getFutureDependencyGraph() { synchronized (dependencyGraphLock) { // Scheduled future will be the most recent one --> Return - if (scheduledFutureDependencyGraph != null) { - return scheduledFutureDependencyGraph; - } - + return Objects.requireNonNullElseGet(scheduledFutureDependencyGraph, // Calculating future will be the most recent one --> Return - if (calculatingFutureDependencyGraph != null) { - return calculatingFutureDependencyGraph; - } - + () -> Objects.requireNonNullElseGet(calculatingFutureDependencyGraph, // No scheduled or calculating future --> Already completed dependency graph is the most recent one - return CompletableFuture.completedFuture(dependencyGraph); + () -> CompletableFuture.completedFuture(dependencyGraph))); } } @@ -5141,11 +5122,7 @@ public void rebuildDependencyGraph() { public Future rebuildDependencyGraphAsync() { synchronized (dependencyGraphLock) { // Collect calls to this method to avoid unnecessary calculation of the dependency graph - if (scheduledFutureDependencyGraph != null) { - return scheduledFutureDependencyGraph; - } - // Schedule new calculation - return scheduledFutureDependencyGraph = scheduleCalculationOfFutureDependencyGraph(500, TimeUnit.MILLISECONDS); + return Objects.requireNonNullElseGet(scheduledFutureDependencyGraph, () -> scheduledFutureDependencyGraph = scheduleCalculationOfFutureDependencyGraph(500, TimeUnit.MILLISECONDS)); } } diff --git a/core/src/main/java/jenkins/model/PeepholePermalink.java b/core/src/main/java/jenkins/model/PeepholePermalink.java index 4fbe5ce340e6..9279883f7b74 100644 --- a/core/src/main/java/jenkins/model/PeepholePermalink.java +++ b/core/src/main/java/jenkins/model/PeepholePermalink.java @@ -98,10 +98,9 @@ Cache.PermalinkTarget get(Job job) { } int resolveNumber(Job job) { - // TODO Java 21+ use patterns var pt = get(job); - if (pt instanceof Cache.Some some) { - return some.number; + if (pt instanceof Cache.Some(int number)) { + return number; } else if (pt instanceof Cache.None) { return 0; } else { // Unknown @@ -266,7 +265,7 @@ public void put(Job job, String id, Known target) { for (var entry : cache.entrySet()) { cw.write(entry.getKey()); cw.write(' '); - cw.write(Integer.toString(entry.getValue() instanceof Cache.Some some ? some.number : -1)); + cw.write(Integer.toString(entry.getValue() instanceof Some(int number) ? number : -1)); cw.write('\n'); } cw.commit(); diff --git a/core/src/main/java/jenkins/model/SimplePageDecorator.java b/core/src/main/java/jenkins/model/SimplePageDecorator.java index 29e08679506c..17bb87990884 100644 --- a/core/src/main/java/jenkins/model/SimplePageDecorator.java +++ b/core/src/main/java/jenkins/model/SimplePageDecorator.java @@ -92,7 +92,7 @@ public static List all() { */ public static SimplePageDecorator first() { List decorators = all(); - return decorators.isEmpty() ? null : decorators.get(0); + return decorators.isEmpty() ? null : decorators.getFirst(); } } diff --git a/core/src/main/java/jenkins/model/queue/ItemDeletion.java b/core/src/main/java/jenkins/model/queue/ItemDeletion.java index b278f4d24c93..5b4aaeb0bc76 100644 --- a/core/src/main/java/jenkins/model/queue/ItemDeletion.java +++ b/core/src/main/java/jenkins/model/queue/ItemDeletion.java @@ -42,7 +42,6 @@ import hudson.model.queue.Tasks; import hudson.model.queue.WorkUnit; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -259,18 +258,11 @@ public static void cancelBuildsInProgress(@NonNull Item initiatingItem) throws F // ItemDeletion happens-before Queue.cancel so we know that the Queue will stay clear // Queue.cancel happens-before collecting the buildsInProgress list // thus buildsInProgress contains the complete set we need to interrupt and wait for - for (Iterator> iterator = - buildsInProgress.entrySet().iterator(); - iterator.hasNext(); ) { - Map.Entry entry = iterator.next(); - // comparison with executor.getCurrentExecutable() == executable currently should always be - // true as we no longer recycle Executors, but safer to future-proof in case we ever - // revisit recycling. - if (!entry.getKey().isActive() - || entry.getValue() != entry.getKey().getCurrentExecutable()) { - iterator.remove(); - } - } + // comparison with executor.getCurrentExecutable() == executable currently should always be + // true as we no longer recycle Executors, but safer to future-proof in case we ever + // revisit recycling. + buildsInProgress.entrySet().removeIf(entry -> !entry.getKey().isActive() + || entry.getValue() != entry.getKey().getCurrentExecutable()); Thread.sleep(50L); } if (!buildsInProgress.isEmpty()) { diff --git a/core/src/main/java/jenkins/model/queue/QueueIdStrategy.java b/core/src/main/java/jenkins/model/queue/QueueIdStrategy.java index 4010ca61c251..de663950d221 100644 --- a/core/src/main/java/jenkins/model/queue/QueueIdStrategy.java +++ b/core/src/main/java/jenkins/model/queue/QueueIdStrategy.java @@ -24,7 +24,7 @@ public static QueueIdStrategy get() { if (strategies.isEmpty()) { return DEFAULT; } - return strategies.get(0); + return strategies.getFirst(); } /** diff --git a/core/src/main/java/jenkins/monitor/OperatingSystemEndOfLifeAdminMonitor.java b/core/src/main/java/jenkins/monitor/OperatingSystemEndOfLifeAdminMonitor.java index 50cf3c9da6f0..7bf49573ca80 100644 --- a/core/src/main/java/jenkins/monitor/OperatingSystemEndOfLifeAdminMonitor.java +++ b/core/src/main/java/jenkins/monitor/OperatingSystemEndOfLifeAdminMonitor.java @@ -109,10 +109,9 @@ void readOperatingSystemList(String initialOperatingSystemJson) throws IOExcepti throw new IOException("Empty data set"); } for (Object systemObj : systems) { - if (!(systemObj instanceof JSONObject)) { + if (!(systemObj instanceof JSONObject system)) { throw new IOException("Wrong object type in data file"); } - JSONObject system = (JSONObject) systemObj; if (!system.has("pattern")) { throw new IOException("Missing pattern in definition file"); diff --git a/core/src/main/java/jenkins/org/apache/commons/validator/routines/DomainValidator.java b/core/src/main/java/jenkins/org/apache/commons/validator/routines/DomainValidator.java index b1d3a42e9f5c..0aa580e57ba3 100644 --- a/core/src/main/java/jenkins/org/apache/commons/validator/routines/DomainValidator.java +++ b/core/src/main/java/jenkins/org/apache/commons/validator/routines/DomainValidator.java @@ -2168,41 +2168,19 @@ public static synchronized void updateTLDOverride(DomainValidator.ArrayType tabl * @since 1.5.1 */ public static synchronized String [] getTLDEntries(ArrayType table) { - final String[] array; - switch (table) { - case COUNTRY_CODE_MINUS: - array = countryCodeTLDsMinus; - break; - case COUNTRY_CODE_PLUS: - array = countryCodeTLDsPlus; - break; - case GENERIC_MINUS: - array = genericTLDsMinus; - break; - case GENERIC_PLUS: - array = genericTLDsPlus; - break; - case LOCAL_MINUS: - array = localTLDsMinus; - break; - case LOCAL_PLUS: - array = localTLDsPlus; - break; - case GENERIC_RO: - array = GENERIC_TLDS; - break; - case COUNTRY_CODE_RO: - array = COUNTRY_CODE_TLDS; - break; - case INFRASTRUCTURE_RO: - array = INFRASTRUCTURE_TLDS; - break; - case LOCAL_RO: - array = LOCAL_TLDS; - break; - default: - throw new IllegalArgumentException(UNEXPECTED_ENUM_VALUE + table); - } + final String[] array = switch (table) { + case COUNTRY_CODE_MINUS -> countryCodeTLDsMinus; + case COUNTRY_CODE_PLUS -> countryCodeTLDsPlus; + case GENERIC_MINUS -> genericTLDsMinus; + case GENERIC_PLUS -> genericTLDsPlus; + case LOCAL_MINUS -> localTLDsMinus; + case LOCAL_PLUS -> localTLDsPlus; + case GENERIC_RO -> GENERIC_TLDS; + case COUNTRY_CODE_RO -> COUNTRY_CODE_TLDS; + case INFRASTRUCTURE_RO -> INFRASTRUCTURE_TLDS; + case LOCAL_RO -> LOCAL_TLDS; + default -> throw new IllegalArgumentException(UNEXPECTED_ENUM_VALUE + table); + }; return Arrays.copyOf(array, array.length); // clone the array } @@ -2214,29 +2192,15 @@ public static synchronized void updateTLDOverride(DomainValidator.ArrayType tabl * @since 1.7 */ public String [] getOverrides(ArrayType table) { - final String[] array; - switch (table) { - case COUNTRY_CODE_MINUS: - array = mycountryCodeTLDsMinus; - break; - case COUNTRY_CODE_PLUS: - array = mycountryCodeTLDsPlus; - break; - case GENERIC_MINUS: - array = mygenericTLDsMinus; - break; - case GENERIC_PLUS: - array = mygenericTLDsPlus; - break; - case LOCAL_MINUS: - array = mylocalTLDsMinus; - break; - case LOCAL_PLUS: - array = mylocalTLDsPlus; - break; - default: - throw new IllegalArgumentException(UNEXPECTED_ENUM_VALUE + table); - } + final String[] array = switch (table) { + case COUNTRY_CODE_MINUS -> mycountryCodeTLDsMinus; + case COUNTRY_CODE_PLUS -> mycountryCodeTLDsPlus; + case GENERIC_MINUS -> mygenericTLDsMinus; + case GENERIC_PLUS -> mygenericTLDsPlus; + case LOCAL_MINUS -> mylocalTLDsMinus; + case LOCAL_PLUS -> mylocalTLDsPlus; + default -> throw new IllegalArgumentException(UNEXPECTED_ENUM_VALUE + table); + }; return Arrays.copyOf(array, array.length); // clone the array } @@ -2270,15 +2234,14 @@ static String unicodeToASCII(String input) { // (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61 // (halfwidth ideographic full stop). char lastChar = input.charAt(length - 1); // fetch original last char - switch (lastChar) { - case '\u002E': // "." full stop - case '\u3002': // ideographic full stop - case '\uFF0E': // fullwidth full stop - case '\uFF61': // halfwidth ideographic full stop - return ascii + "."; // restore the missing stop - default: - return ascii; - } + return switch (lastChar) { + case '\u002E', // "." full stop + '\u3002', // ideographic full stop + '\uFF0E', // fullwidth full stop + '\uFF61' // halfwidth ideographic full stop + -> ascii + "."; // restore the missing stop + default -> ascii; + }; } catch (IllegalArgumentException e) { // input is not valid return input; } diff --git a/core/src/main/java/jenkins/org/apache/commons/validator/routines/InetAddressValidator.java b/core/src/main/java/jenkins/org/apache/commons/validator/routines/InetAddressValidator.java index 71e937d02b72..50e5e30e945b 100644 --- a/core/src/main/java/jenkins/org/apache/commons/validator/routines/InetAddressValidator.java +++ b/core/src/main/java/jenkins/org/apache/commons/validator/routines/InetAddressValidator.java @@ -175,7 +175,7 @@ public boolean isValidInet6Address(String inet6Address) { // String.split() drops ending empty segments octetList.add(""); } else if (inet6Address.startsWith("::") && !octetList.isEmpty()) { - octetList.remove(0); + octetList.removeFirst(); } octets = octetList.toArray(new String[0]); } diff --git a/core/src/main/java/jenkins/scm/SCMCheckoutStrategy.java b/core/src/main/java/jenkins/scm/SCMCheckoutStrategy.java index 2645ce9cbad4..b8118c2caac6 100644 --- a/core/src/main/java/jenkins/scm/SCMCheckoutStrategy.java +++ b/core/src/main/java/jenkins/scm/SCMCheckoutStrategy.java @@ -69,9 +69,8 @@ public abstract class SCMCheckoutStrategy implements Describable build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { AbstractProject project = build.getProject(); - if (project instanceof BuildableItemWithBuildWrappers) { - BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project; - for (BuildWrapper bw : biwbw.getBuildWrappersList()) + if (project instanceof BuildableItemWithBuildWrappers biwbw) { + for (BuildWrapper bw : biwbw.getBuildWrappersList()) bw.preCheckout(build, launcher, listener); } } diff --git a/core/src/main/java/jenkins/security/ApiTokenProperty.java b/core/src/main/java/jenkins/security/ApiTokenProperty.java index 34ed7347be90..e94e36fc44e6 100644 --- a/core/src/main/java/jenkins/security/ApiTokenProperty.java +++ b/core/src/main/java/jenkins/security/ApiTokenProperty.java @@ -347,27 +347,30 @@ public UserProperty reconfigure(StaplerRequest2 req, @CheckForNull JSONObject fo } private Map convertToTokenMap(Object tokenStoreData) { - if (tokenStoreData == null) { - // in case there are no token - return Collections.emptyMap(); - } else if (tokenStoreData instanceof JSONObject) { - // in case there is only one token - JSONObject singleTokenData = (JSONObject) tokenStoreData; - Map result = new HashMap<>(); - addJSONTokenIntoMap(result, singleTokenData); - return result; - } else if (tokenStoreData instanceof JSONArray) { - // in case there are multiple tokens - JSONArray tokenArray = (JSONArray) tokenStoreData; - Map result = new HashMap<>(); - for (int i = 0; i < tokenArray.size(); i++) { - JSONObject tokenData = tokenArray.getJSONObject(i); - addJSONTokenIntoMap(result, tokenData); - } - return result; - } - - throw HttpResponses.error(400, "Unexpected class received for the token store information"); + switch (tokenStoreData) { + case null -> { + // in case there are no token + return Collections.emptyMap(); + } + case JSONObject singleTokenData -> { + // in case there is only one token + Map result = new HashMap<>(); + addJSONTokenIntoMap(result, singleTokenData); + return result; + } + case JSONArray tokenArray -> { + // in case there are multiple tokens + Map result = new HashMap<>(); + for (int i = 0; i < tokenArray.size(); i++) { + JSONObject tokenData = tokenArray.getJSONObject(i); + addJSONTokenIntoMap(result, tokenData); + } + return result; + } + default -> { + throw HttpResponses.error(400, "Unexpected class received for the token store information"); + } + } } private void addJSONTokenIntoMap(Map tokenMap, JSONObject tokenData) { diff --git a/core/src/main/java/jenkins/security/ImpersonatingExecutorService.java b/core/src/main/java/jenkins/security/ImpersonatingExecutorService.java index 4a2249dd4f0f..5a3794eaabad 100644 --- a/core/src/main/java/jenkins/security/ImpersonatingExecutorService.java +++ b/core/src/main/java/jenkins/security/ImpersonatingExecutorService.java @@ -61,24 +61,18 @@ public ImpersonatingExecutorService(ExecutorService base, org.acegisecurity.Auth @Override protected Runnable wrap(final Runnable r) { - return new Runnable() { - @Override - public void run() { - try (ACLContext ctxt = ACL.as2(authentication)) { - r.run(); - } + return () -> { + try (ACLContext ctxt = ACL.as2(authentication)) { + r.run(); } }; } @Override protected Callable wrap(final Callable r) { - return new Callable<>() { - @Override - public V call() throws Exception { - try (ACLContext ctxt = ACL.as2(authentication)) { - return r.call(); - } + return () -> { + try (ACLContext ctxt = ACL.as2(authentication)) { + return r.call(); } }; } diff --git a/core/src/main/java/jenkins/security/ImpersonatingScheduledExecutorService.java b/core/src/main/java/jenkins/security/ImpersonatingScheduledExecutorService.java index 992213547a81..b5ff60112c67 100644 --- a/core/src/main/java/jenkins/security/ImpersonatingScheduledExecutorService.java +++ b/core/src/main/java/jenkins/security/ImpersonatingScheduledExecutorService.java @@ -60,24 +60,18 @@ public ImpersonatingScheduledExecutorService(ScheduledExecutorService base, org. @Override protected Runnable wrap(final Runnable r) { - return new Runnable() { - @Override - public void run() { - try (ACLContext ctxt = ACL.as2(authentication)) { - r.run(); - } + return () -> { + try (ACLContext ctxt = ACL.as2(authentication)) { + r.run(); } }; } @Override protected Callable wrap(final Callable r) { - return new Callable<>() { - @Override - public V call() throws Exception { - try (ACLContext ctxt = ACL.as2(authentication)) { - return r.call(); - } + return () -> { + try (ACLContext ctxt = ACL.as2(authentication)) { + return r.call(); } }; } diff --git a/core/src/main/java/jenkins/security/NonSerializableSecurityContext.java b/core/src/main/java/jenkins/security/NonSerializableSecurityContext.java index 859b0db4ef1b..52c21eda2c33 100644 --- a/core/src/main/java/jenkins/security/NonSerializableSecurityContext.java +++ b/core/src/main/java/jenkins/security/NonSerializableSecurityContext.java @@ -59,8 +59,7 @@ public NonSerializableSecurityContext(Authentication authentication) { @Override public boolean equals(Object obj) { - if (obj instanceof SecurityContext) { - SecurityContext test = (SecurityContext) obj; + if (obj instanceof SecurityContext test) { if (this.getAuthentication() == null && test.getAuthentication() == null) { return true; diff --git a/core/src/main/java/jenkins/security/ResourceDomainRootAction.java b/core/src/main/java/jenkins/security/ResourceDomainRootAction.java index bd327599bd2f..e38ccdbe2774 100644 --- a/core/src/main/java/jenkins/security/ResourceDomainRootAction.java +++ b/core/src/main/java/jenkins/security/ResourceDomainRootAction.java @@ -183,7 +183,7 @@ public Token getToken(@NonNull DirectoryBrowserSupport dbs, @NonNull StaplerRequ // Now get the 'restOfUrl' after the top-level ancestor (which is the Jenkins singleton). // In other words, this is the complete URL after Jenkins handled the top-level request. - final String completeUrl = req.getAncestors().get(0).getRestOfUrl(); + final String completeUrl = req.getAncestors().getFirst().getRestOfUrl(); // And finally, remove the 'restOfPath' suffix from the complete URL, as that's the path from Jenkins to the DBS. String dbsUrl = completeUrl.substring(0, completeUrl.length() - dbsFile.length()); diff --git a/core/src/main/java/jenkins/security/SecurityContextExecutorService.java b/core/src/main/java/jenkins/security/SecurityContextExecutorService.java index 372003f0dfe3..fa4dc71d1025 100644 --- a/core/src/main/java/jenkins/security/SecurityContextExecutorService.java +++ b/core/src/main/java/jenkins/security/SecurityContextExecutorService.java @@ -52,16 +52,13 @@ public SecurityContextExecutorService(ExecutorService service) { @Override protected Runnable wrap(final Runnable r) { final SecurityContext callingContext = getContext(); - return new Runnable() { - @Override - public void run() { - SecurityContext old = getContext(); - setContext(callingContext); - try { - r.run(); - } finally { - setContext(old); - } + return () -> { + SecurityContext old = getContext(); + setContext(callingContext); + try { + r.run(); + } finally { + setContext(old); } }; } @@ -69,16 +66,13 @@ public void run() { @Override protected Callable wrap(final Callable c) { final SecurityContext callingContext = getContext(); - return new Callable<>() { - @Override - public V call() throws Exception { - SecurityContext old = getContext(); - setContext(callingContext); - try { - return c.call(); - } finally { - setContext(old); - } + return () -> { + SecurityContext old = getContext(); + setContext(callingContext); + try { + return c.call(); + } finally { + setContext(old); } }; } diff --git a/core/src/main/java/jenkins/security/csp/impl/CspDecorator.java b/core/src/main/java/jenkins/security/csp/impl/CspDecorator.java index 54434d937508..07982cdb01db 100644 --- a/core/src/main/java/jenkins/security/csp/impl/CspDecorator.java +++ b/core/src/main/java/jenkins/security/csp/impl/CspDecorator.java @@ -79,7 +79,7 @@ public String getReportingEndpointsHeaderValue(HttpServletRequest req) { if (staplerRequest2 != null) { final List ancestors = staplerRequest2.getAncestors(); if (!ancestors.isEmpty()) { - final Ancestor nearest = ancestors.get(ancestors.size() - 1); + final Ancestor nearest = ancestors.getLast(); restOfPath = nearest.getRestOfUrl(); modelObjectClass = nearest.getObject().getClass(); } diff --git a/core/src/main/java/jenkins/util/AtmostOneTaskExecutor.java b/core/src/main/java/jenkins/util/AtmostOneTaskExecutor.java index 6347842856f1..ee50280d9474 100644 --- a/core/src/main/java/jenkins/util/AtmostOneTaskExecutor.java +++ b/core/src/main/java/jenkins/util/AtmostOneTaskExecutor.java @@ -93,32 +93,29 @@ public synchronized Future submit() { * but {@link #inprogress} is null (meaning none is executing right now), * get one going. */ - @SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "method signature does not permit plumbing through the return value") + @SuppressFBWarnings(value = {"RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", "IS2_INCONSISTENT_SYNC"}, justification = "method signature does not permit plumbing through the return value") private synchronized void maybeRun() { if (inprogress == null && pending != null) { - base.submit(new Callable() { - @Override - public Void call() throws Exception { - synchronized (AtmostOneTaskExecutor.this) { - // everyone who submits after this should form a next batch - inprogress = pending; - pending = null; - } + base.submit((Callable) () -> { + synchronized (AtmostOneTaskExecutor.this) { + // everyone who submits after this should form a next batch + inprogress = pending; + pending = null; + } - try { - inprogress.complete(task.call()); - } catch (Throwable t) { - LOGGER.log(Level.WARNING, null, t); - inprogress.completeExceptionally(t); - } finally { - synchronized (AtmostOneTaskExecutor.this) { - // if next one is pending, get that scheduled - inprogress = null; - maybeRun(); - } + try { + inprogress.complete(task.call()); + } catch (Throwable t) { + LOGGER.log(Level.WARNING, null, t); + inprogress.completeExceptionally(t); + } finally { + synchronized (AtmostOneTaskExecutor.this) { + // if next one is pending, get that scheduled + inprogress = null; + maybeRun(); } - return null; } + return null; }); } } diff --git a/core/src/main/java/jenkins/util/ContextResettingExecutorService.java b/core/src/main/java/jenkins/util/ContextResettingExecutorService.java index f6a8c0407a56..c60ea786a896 100644 --- a/core/src/main/java/jenkins/util/ContextResettingExecutorService.java +++ b/core/src/main/java/jenkins/util/ContextResettingExecutorService.java @@ -18,36 +18,30 @@ public ContextResettingExecutorService(ExecutorService base) { @Override protected Runnable wrap(final Runnable r) { - return new Runnable() { - @Override - public void run() { - Thread t = Thread.currentThread(); - String name = t.getName(); - ClassLoader cl = t.getContextClassLoader(); - try { - r.run(); - } finally { - t.setName(name); - t.setContextClassLoader(cl); - } + return () -> { + Thread t = Thread.currentThread(); + String name = t.getName(); + ClassLoader cl = t.getContextClassLoader(); + try { + r.run(); + } finally { + t.setName(name); + t.setContextClassLoader(cl); } }; } @Override protected Callable wrap(final Callable r) { - return new Callable<>() { - @Override - public V call() throws Exception { - Thread t = Thread.currentThread(); - String name = t.getName(); - ClassLoader cl = t.getContextClassLoader(); - try { - return r.call(); - } finally { - t.setName(name); - t.setContextClassLoader(cl); - } + return () -> { + Thread t = Thread.currentThread(); + String name = t.getName(); + ClassLoader cl = t.getContextClassLoader(); + try { + return r.call(); + } finally { + t.setName(name); + t.setContextClassLoader(cl); } }; } diff --git a/core/src/main/java/jenkins/util/ErrorLoggingScheduledThreadPoolExecutor.java b/core/src/main/java/jenkins/util/ErrorLoggingScheduledThreadPoolExecutor.java index 7618ac476195..80b09bf031b4 100644 --- a/core/src/main/java/jenkins/util/ErrorLoggingScheduledThreadPoolExecutor.java +++ b/core/src/main/java/jenkins/util/ErrorLoggingScheduledThreadPoolExecutor.java @@ -61,8 +61,7 @@ class ErrorLoggingScheduledThreadPoolExecutor extends ScheduledThreadPoolExecuto @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); - if (t == null && r instanceof Future) { - Future f = (Future) r; + if (t == null && r instanceof Future f) { if (f.isDone()) { // TODO super Javadoc does not suggest this, but without it, we hang in FutureTask.awaitDone! try { f.get(/* just to be on the safe side, do not wait */0, TimeUnit.NANOSECONDS); diff --git a/core/src/main/java/jenkins/util/JSONSignatureValidator.java b/core/src/main/java/jenkins/util/JSONSignatureValidator.java index 10341347329c..38d2f629189d 100644 --- a/core/src/main/java/jenkins/util/JSONSignatureValidator.java +++ b/core/src/main/java/jenkins/util/JSONSignatureValidator.java @@ -98,7 +98,7 @@ public FormValidation verifySignature(JSONObject o) throws IOException { try { MessageDigest digest = MessageDigest.getInstance("SHA-512"); Signature sig = Signature.getInstance("SHA512withRSA"); - sig.initVerify(certs.get(0)); + sig.initVerify(certs.getFirst()); resultSha512 = checkSpecificSignature(o, signature, digest, "correct_digest512", sig, "correct_signature512", "SHA-512"); switch (resultSha512.kind) { case ERROR: @@ -119,7 +119,7 @@ public FormValidation verifySignature(JSONObject o) throws IOException { MessageDigest digest = MessageDigest.getInstance("SHA1"); Signature sig = Signature.getInstance("SHA1withRSA"); - sig.initVerify(certs.get(0)); + sig.initVerify(certs.getFirst()); FormValidation resultSha1 = checkSpecificSignature(o, signature, digest, "correct_digest", sig, "correct_signature", "SHA-1"); switch (resultSha1.kind) { @@ -261,8 +261,7 @@ protected Set loadTrustAnchors(CertificateFactory cf) throws IOExce try (InputStream in = j.getServletContext().getResourceAsStream(cert)) { if (in == null) continue; // our test for paths ending in / should prevent this from happening certificate = cf.generateCertificate(in); - if (certificate instanceof X509Certificate) { - X509Certificate c = (X509Certificate) certificate; + if (certificate instanceof X509Certificate c) { LOGGER.log(Level.FINE, "Add CA certificate found in webapp resources:\n\tsubjectDN: {0}\n\tissuer: {1}\n\tnotBefore: {2}\n\tnotAfter: {3}", new Object[] { c.getSubjectDN(), c.getIssuerDN(), c.getNotBefore(), c.getNotAfter() }); } @@ -294,8 +293,7 @@ protected Set loadTrustAnchors(CertificateFactory cf) throws IOExce Certificate certificate; try (InputStream in = Files.newInputStream(cert.toPath())) { certificate = cf.generateCertificate(in); - if (certificate instanceof X509Certificate) { - X509Certificate c = (X509Certificate) certificate; + if (certificate instanceof X509Certificate c) { LOGGER.log(Level.FINE, "Add CA certificate found in Jenkins home:\n\tsubjectDN: {0}\n\tissuer: {1}\n\tnotBefore: {2}\n\tnotAfter: {3}", new Object[] { c.getSubjectDN(), c.getIssuerDN(), c.getNotBefore(), c.getNotAfter() }); } diff --git a/core/src/main/java/jenkins/util/ProgressiveRendering.java b/core/src/main/java/jenkins/util/ProgressiveRendering.java index 3fca29afbf96..9cc8f057cd62 100644 --- a/core/src/main/java/jenkins/util/ProgressiveRendering.java +++ b/core/src/main/java/jenkins/util/ProgressiveRendering.java @@ -28,7 +28,6 @@ import hudson.model.AbstractItem; import jakarta.servlet.http.HttpServletRequest; import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; @@ -111,33 +110,29 @@ protected ProgressiveRendering() { boundId = ancestor.getNextToken(0); LOG.log(Level.FINE, "starting rendering {0} at {1}", new Object[] {uri, boundId}); final ExecutorService executorService = executorService(); - executorService.submit(new Runnable() { - @Override public void run() { - lastNewsTime = start = System.currentTimeMillis(); - setCurrentRequest(request); - SecurityContext orig = SecurityContextHolder.getContext(); - try { - SecurityContextHolder.setContext(securityContext); - compute(); - if (status != CANCELED && status != ERROR) { - status = 1; - } - } catch (Exception x) { - LOG.log(Level.WARNING, "failed to compute " + uri, x); - status = ERROR; - } finally { - SecurityContextHolder.setContext(orig); - setCurrentRequest(null); - LOG.log(Level.FINE, "{0} finished in {1}msec with status {2}", new Object[] {uri, System.currentTimeMillis() - start, status}); - } - if (executorService instanceof ScheduledExecutorService) { - ((ScheduledExecutorService) executorService).schedule(new Runnable() { - @Override public void run() { - LOG.log(Level.FINE, "some time has elapsed since {0} finished, so releasing", boundId); - boundObjectTable.release(boundId); - } - }, timeout() /* add some grace period for browser/network overhead */ * 2, TimeUnit.MILLISECONDS); + executorService.submit(() -> { + lastNewsTime = start = System.currentTimeMillis(); + setCurrentRequest(request); + SecurityContext orig = SecurityContextHolder.getContext(); + try { + SecurityContextHolder.setContext(securityContext); + compute(); + if (status != CANCELED && status != ERROR) { + status = 1; } + } catch (Exception x) { + LOG.log(Level.WARNING, "failed to compute " + uri, x); + status = ERROR; + } finally { + SecurityContextHolder.setContext(orig); + setCurrentRequest(null); + LOG.log(Level.FINE, "{0} finished in {1}msec with status {2}", new Object[] {uri, System.currentTimeMillis() - start, status}); + } + if (executorService instanceof ScheduledExecutorService) { + ((ScheduledExecutorService) executorService).schedule(() -> { + LOG.log(Level.FINE, "some time has elapsed since {0} finished, so releasing", boundId); + boundObjectTable.release(boundId); + }, timeout() /* add some grace period for browser/network overhead */ * 2, TimeUnit.MILLISECONDS); } }); } @@ -168,14 +163,12 @@ private static RequestImpl createMockRequest() { List/**/ ancestors = currentRequest.ancestors; LOG.log(Level.FINER, "mocking ancestors {0} using {1}", new Object[] {ancestors, getters}); TokenList tokens = currentRequest.tokens; - return new RequestImpl(Stapler.getCurrent(), (HttpServletRequest) Proxy.newProxyInstance(ProgressiveRendering.class.getClassLoader(), new Class[] {HttpServletRequest.class}, new InvocationHandler() { - @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - String m = method.getName(); - if (getters.containsKey(m)) { - return getters.get(m); - } else { // TODO implement other methods as needed - throw new UnsupportedOperationException(m); - } + return new RequestImpl(Stapler.getCurrent(), (HttpServletRequest) Proxy.newProxyInstance(ProgressiveRendering.class.getClassLoader(), new Class[] {HttpServletRequest.class}, (proxy, method, args) -> { + String m = method.getName(); + if (getters.containsKey(m)) { + return getters.get(m); + } else { // TODO implement other methods as needed + throw new UnsupportedOperationException(m); } }), ancestors, tokens); } diff --git a/core/src/main/java/jenkins/util/java/JavaUtils.java b/core/src/main/java/jenkins/util/java/JavaUtils.java index 30d43f8ed281..88a146ce2481 100644 --- a/core/src/main/java/jenkins/util/java/JavaUtils.java +++ b/core/src/main/java/jenkins/util/java/JavaUtils.java @@ -59,6 +59,6 @@ public static JavaSpecificationVersion getCurrentJavaRuntimeVersionNumber() { */ public static String getCurrentRuntimeJavaVersion() { Runtime.Version runtimeVersion = Runtime.version(); - return String.valueOf(runtimeVersion.version().get(0)); + return String.valueOf(runtimeVersion.version().getFirst()); } } diff --git a/core/src/main/java/jenkins/util/xstream/XStreamDOM.java b/core/src/main/java/jenkins/util/xstream/XStreamDOM.java index 4a09db46d880..5fe3f6c9052d 100644 --- a/core/src/main/java/jenkins/util/xstream/XStreamDOM.java +++ b/core/src/main/java/jenkins/util/xstream/XStreamDOM.java @@ -487,7 +487,7 @@ public HierarchicalStreamWriter underlyingWriter() { public XStreamDOM getOutput() { if (pendings.size() != 1) throw new IllegalStateException(); - return pendings.peek().children.get(0); + return pendings.peek().children.getFirst(); } } diff --git a/core/src/main/java/jenkins/widgets/HistoryPageEntry.java b/core/src/main/java/jenkins/widgets/HistoryPageEntry.java index 2770fa928b02..668cbb5eaad2 100644 --- a/core/src/main/java/jenkins/widgets/HistoryPageEntry.java +++ b/core/src/main/java/jenkins/widgets/HistoryPageEntry.java @@ -55,15 +55,13 @@ public long getEntryId() { } protected static long getEntryId(@NonNull Object entry) { - if (entry instanceof QueueItem) { - return ((QueueItem) entry).getId(); - } else if (entry instanceof HistoricalBuild run) { - return Long.MIN_VALUE + run.getNumber(); - } else if (entry instanceof Number) { - // Used for testing purposes because of JENKINS-30899 and JENKINS-30909 - return Long.MIN_VALUE + ((Number) entry).longValue(); - } else { - return Run.QUEUE_ID_UNKNOWN; - } + return switch (entry) { + case QueueItem queueItem -> queueItem.getId(); + case HistoricalBuild run -> Long.MIN_VALUE + run.getNumber(); + case Number number -> + // Used for testing purposes because of JENKINS-30899 and JENKINS-30909 + Long.MIN_VALUE + number.longValue(); + default -> Run.QUEUE_ID_UNKNOWN; + }; } } diff --git a/core/src/main/java/jenkins/widgets/HistoryPageFilter.java b/core/src/main/java/jenkins/widgets/HistoryPageFilter.java index a6216ca547ef..3b23c4852a50 100644 --- a/core/src/main/java/jenkins/widgets/HistoryPageFilter.java +++ b/core/src/main/java/jenkins/widgets/HistoryPageFilter.java @@ -230,14 +230,11 @@ private void sort(List items) { // Queue items can start building out of order with how they got added to the queue. Sorting them // before adding to the page. They'll still get displayed before the building items coz they end // up in a different list in HistoryPageFilter. - items.sort(new Comparator() { - @Override - public int compare(Object o1, Object o2) { - long o1QID = HistoryPageEntry.getEntryId(o1); - long o2QID = HistoryPageEntry.getEntryId(o2); + items.sort((Comparator) (o1, o2) -> { + long o1QID = HistoryPageEntry.getEntryId(o1); + long o2QID = HistoryPageEntry.getEntryId(o2); - return Long.compare(o2QID, o1QID); - } + return Long.compare(o2QID, o1QID); }); } @@ -261,7 +258,7 @@ private void addRun(HistoricalBuild run) { HistoryPageEntry entry = new HistoryPageEntry<>(run); // Assert that runs have been added in descending order if (!runs.isEmpty()) { - if (entry.getEntryId() > runs.get(runs.size() - 1).getEntryId()) { + if (entry.getEntryId() > runs.getLast().getEntryId()) { throw new IllegalStateException("Cannot add newer " + run + " to descending-order list " + runs.stream().map(HistoryPageEntry::getEntry).collect(Collectors.toList())); } @@ -278,8 +275,7 @@ private void updateNewestOldest(long entryId) { private boolean add(Object entry) { // Purposely not calling isFull(). May need to add a greater number of entries // to the page initially, newerThan then cutting it back down to size using cutLeading() - if (entry instanceof QueueItem) { - QueueItem item = (QueueItem) entry; + if (entry instanceof QueueItem item) { if (searchString != null && !fitsSearchParams(item)) { return false; } diff --git a/core/src/main/java/org/acegisecurity/AuthenticationException.java b/core/src/main/java/org/acegisecurity/AuthenticationException.java index 22a3fc398015..d6fed263bfda 100644 --- a/core/src/main/java/org/acegisecurity/AuthenticationException.java +++ b/core/src/main/java/org/acegisecurity/AuthenticationException.java @@ -76,29 +76,30 @@ public org.springframework.security.core.AuthenticationException toSpring() { * @return either an {@link AuthenticationException} or a {@link DataAccessException} */ public static RuntimeException fromSpring(org.springframework.security.core.AuthenticationException x) { - if (x instanceof org.springframework.security.authentication.BadCredentialsException) { - return BadCredentialsException.fromSpring((org.springframework.security.authentication.BadCredentialsException) x); - } else if (x instanceof org.springframework.security.authentication.AuthenticationServiceException) { - return AuthenticationServiceException.fromSpring((org.springframework.security.authentication.AuthenticationServiceException) x); - } else if (x instanceof org.springframework.security.authentication.AccountExpiredException) { - return AccountExpiredException.fromSpring((org.springframework.security.authentication.AccountExpiredException) x); - } else if (x instanceof org.springframework.security.authentication.CredentialsExpiredException) { - return CredentialsExpiredException.fromSpring((org.springframework.security.authentication.CredentialsExpiredException) x); - } else if (x instanceof org.springframework.security.authentication.DisabledException) { - return DisabledException.fromSpring((org.springframework.security.authentication.DisabledException) x); - } else if (x instanceof org.springframework.security.authentication.InsufficientAuthenticationException) { - return InsufficientAuthenticationException.fromSpring((org.springframework.security.authentication.InsufficientAuthenticationException) x); - } else if (x instanceof org.springframework.security.authentication.LockedException) { - return LockedException.fromSpring((org.springframework.security.authentication.LockedException) x); - } else if (x instanceof org.springframework.security.authentication.ProviderNotFoundException) { - return ProviderNotFoundException.fromSpring((org.springframework.security.authentication.ProviderNotFoundException) x); - } else if (x instanceof UserMayOrMayNotExistException2 && x.getCause() instanceof DataAccessException) { - return (DataAccessException) x.getCause(); - } else if (x instanceof org.springframework.security.core.userdetails.UsernameNotFoundException) { - return UsernameNotFoundException.fromSpring((org.springframework.security.core.userdetails.UsernameNotFoundException) x); - } else { - return new AuthenticationException(x.toString(), x) {}; - } + return switch (x) { + case org.springframework.security.authentication.BadCredentialsException badCredentialsException -> + BadCredentialsException.fromSpring(badCredentialsException); + case org.springframework.security.authentication.AuthenticationServiceException authenticationServiceException -> + AuthenticationServiceException.fromSpring(authenticationServiceException); + case org.springframework.security.authentication.AccountExpiredException accountExpiredException -> + AccountExpiredException.fromSpring(accountExpiredException); + case org.springframework.security.authentication.CredentialsExpiredException credentialsExpiredException -> + CredentialsExpiredException.fromSpring(credentialsExpiredException); + case org.springframework.security.authentication.DisabledException disabledException -> + DisabledException.fromSpring(disabledException); + case org.springframework.security.authentication.InsufficientAuthenticationException insufficientAuthenticationException -> + InsufficientAuthenticationException.fromSpring(insufficientAuthenticationException); + case org.springframework.security.authentication.LockedException lockedException -> + LockedException.fromSpring(lockedException); + case org.springframework.security.authentication.ProviderNotFoundException providerNotFoundException -> + ProviderNotFoundException.fromSpring(providerNotFoundException); + case UserMayOrMayNotExistException2 userMayOrMayNotExistException2 when x.getCause() instanceof DataAccessException -> + (DataAccessException) x.getCause(); + case org.springframework.security.core.userdetails.UsernameNotFoundException usernameNotFoundException -> + UsernameNotFoundException.fromSpring(usernameNotFoundException); + default -> new AuthenticationException(x.toString(), x) { + }; + }; } } diff --git a/core/src/main/java/org/jenkins/ui/icon/IconType.java b/core/src/main/java/org/jenkins/ui/icon/IconType.java index c7e581c2330f..dff97088e08e 100644 --- a/core/src/main/java/org/jenkins/ui/icon/IconType.java +++ b/core/src/main/java/org/jenkins/ui/icon/IconType.java @@ -45,15 +45,10 @@ public enum IconType { */ public String toQualifiedUrl(String url, String resURL) { - switch (this) { - case CORE: { - return resURL + "/images/" + url; - } - case PLUGIN: { - return resURL + "/plugin/" + url; - } - default: - throw new AssertionError("Unknown icon type: " + this); - } + return switch (this) { + case CORE -> resURL + "/images/" + url; + case PLUGIN -> resURL + "/plugin/" + url; + default -> throw new AssertionError("Unknown icon type: " + this); + }; } } diff --git a/core/src/test/java/hudson/MarkupTextTest.java b/core/src/test/java/hudson/MarkupTextTest.java index d445abecce34..a091a2cab831 100644 --- a/core/src/test/java/hudson/MarkupTextTest.java +++ b/core/src/test/java/hudson/MarkupTextTest.java @@ -61,8 +61,8 @@ void findTokensOnSubText() { MarkupText t = new MarkupText("Fixed 2 issues in this commit, fixing issue 155, 145"); List tokens = t.findTokens(Pattern.compile("issue .*")); assertEquals(1, tokens.size(), "Expected one token"); - assertEquals("issue 155, 145", tokens.get(0).group(0), "Expected single token was incorrect"); - for (SubText st : tokens.get(0).findTokens(Pattern.compile("([0-9]+)"))) + assertEquals("issue 155, 145", tokens.getFirst().group(0), "Expected single token was incorrect"); + for (SubText st : tokens.getFirst().findTokens(Pattern.compile("([0-9]+)"))) st.surroundWith("<$1>", "<$1>"); assertEquals("Fixed 2 issues in this commit, fixing issue <155>155<155>, <145>145<145>", t.toString(false)); diff --git a/core/src/test/java/hudson/logging/LogRecorderTest.java b/core/src/test/java/hudson/logging/LogRecorderTest.java index 4d8fc2dbb2ff..0e267a87fe66 100644 --- a/core/src/test/java/hudson/logging/LogRecorderTest.java +++ b/core/src/test/java/hudson/logging/LogRecorderTest.java @@ -81,7 +81,7 @@ void testClearing() throws IOException { LogRecord record = createLogRecord("jenkins", Level.INFO, "message"); lr.handler.publish(record); - assertEquals(lr.handler.getView().get(0), record); + assertEquals(lr.handler.getView().getFirst(), record); assertEquals(1, lr.handler.getView().size()); lr.doClear(); diff --git a/core/src/test/java/hudson/model/RunTest.java b/core/src/test/java/hudson/model/RunTest.java index af5950fb17aa..a8f2efd58846 100644 --- a/core/src/test/java/hudson/model/RunTest.java +++ b/core/src/test/java/hudson/model/RunTest.java @@ -195,7 +195,7 @@ void getLogReturnsAnRightOrder() throws Exception { assertEquals("dummy" + (10 + i), logLines.get(i)); } int truncatedCount = 10 * ("dummyN".length() + System.lineSeparator().length()) - 2; - assertEquals("[...truncated " + truncatedCount + " B...]", logLines.get(0)); + assertEquals("[...truncated " + truncatedCount + " B...]", logLines.getFirst()); } @SuppressWarnings("deprecation") diff --git a/core/src/test/java/hudson/model/ViewTest.java b/core/src/test/java/hudson/model/ViewTest.java index 69f6ea359170..a886cd210e22 100644 --- a/core/src/test/java/hudson/model/ViewTest.java +++ b/core/src/test/java/hudson/model/ViewTest.java @@ -57,7 +57,7 @@ void testAddDisplayNamesToSearchIndex() { List result = new ArrayList<>(); index.find(displayName1, result); assertEquals(1, result.size()); - SearchItem actual = result.get(0); + SearchItem actual = result.getFirst(); assertEquals(actual.getSearchName(), item1.getDisplayName()); assertEquals(actual.getSearchUrl(), item1.getSearchUrl()); @@ -66,7 +66,7 @@ void testAddDisplayNamesToSearchIndex() { // make sure we can fetch item 2 from the index index.find(displayName2, result); assertEquals(1, result.size()); - actual = result.get(0); + actual = result.getFirst(); assertEquals(actual.getSearchName(), item2.getDisplayName()); assertEquals(actual.getSearchUrl(), item2.getSearchUrl()); } diff --git a/core/src/test/java/hudson/util/CopyOnWriteListTest.java b/core/src/test/java/hudson/util/CopyOnWriteListTest.java index 47f8e7b85af2..e5ed3006e66f 100644 --- a/core/src/test/java/hudson/util/CopyOnWriteListTest.java +++ b/core/src/test/java/hudson/util/CopyOnWriteListTest.java @@ -73,7 +73,7 @@ void serialization() { assertThat(out, isSimilarTo(expected).ignoreWhitespace() .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))); td2 = (TestData) xs.fromXML(out); - assertEquals("foobar1", td2.list1.getView().get(0)); - assertEquals("foobar2", td2.list2.get(0)); + assertEquals("foobar1", td2.list1.getView().getFirst()); + assertEquals("foobar2", td2.list2.getFirst()); } } diff --git a/core/src/test/java/hudson/util/io/TarArchiverTest.java b/core/src/test/java/hudson/util/io/TarArchiverTest.java index e154d2309580..ddd899496e00 100644 --- a/core/src/test/java/hudson/util/io/TarArchiverTest.java +++ b/core/src/test/java/hudson/util/io/TarArchiverTest.java @@ -100,7 +100,7 @@ void permission() throws Exception { // extract via the zip command e.deleteContents(); run(e, "unzip", zip.getAbsolutePath()); - e = e.listDirectories().get(0); + e = e.listDirectories().getFirst(); assertEquals(0755, e.child("a.txt").mode()); assertEquals(dirMode, e.child("subdir").mode()); diff --git a/core/src/test/java/jenkins/plugins/DetachedPluginsUtilTest.java b/core/src/test/java/jenkins/plugins/DetachedPluginsUtilTest.java index 58c476af10b9..6ca9cb2d41e0 100644 --- a/core/src/test/java/jenkins/plugins/DetachedPluginsUtilTest.java +++ b/core/src/test/java/jenkins/plugins/DetachedPluginsUtilTest.java @@ -24,7 +24,7 @@ void checkJaxb() { .toList(); assertEquals(1, plugins.size()); - DetachedPluginsUtil.DetachedPlugin jaxb = plugins.get(0); + DetachedPluginsUtil.DetachedPlugin jaxb = plugins.getFirst(); final List detachedPlugins = mapToPluginShortName(DetachedPluginsUtil.getDetachedPlugins()); assertThat(detachedPlugins, hasItem("jaxb")); diff --git a/core/src/test/java/jenkins/security/csp/CspBuilderTest.java b/core/src/test/java/jenkins/security/csp/CspBuilderTest.java index 314012a39e44..de5b6826533b 100644 --- a/core/src/test/java/jenkins/security/csp/CspBuilderTest.java +++ b/core/src/test/java/jenkins/security/csp/CspBuilderTest.java @@ -318,7 +318,7 @@ void testGetMergedDirectivesValuesAreImmutable() { builder.add(Directive.DEFAULT_SRC, Directive.SELF); List merged = builder.getMergedDirectives(); - Directive directive = merged.get(0); + Directive directive = merged.getFirst(); assertThrows(UnsupportedOperationException.class, () -> directive.values().add("should-fail")); } diff --git a/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java b/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java index d71844bf37d4..92a10f427631 100644 --- a/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java +++ b/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java @@ -186,7 +186,7 @@ void escapeHandling() throws Exception { String input = getTestData("XStreamDOMTest.data3.xml"); XStreamDOM dom = XStreamDOM.from(new StringReader(input)); - List children = dom.getChildren().get(0).getChildren().get(0).getChildren(); + List children = dom.getChildren().getFirst().getChildren().getFirst().getChildren(); assertNamesAreEscaped(children); Foo foo = (Foo) xs.fromXML(new StringReader(input)); diff --git a/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java b/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java index 160cb7cd3634..35d437925041 100644 --- a/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java +++ b/core/src/test/java/jenkins/widgets/HistoryPageFilterTest.java @@ -117,9 +117,9 @@ void test_latest_longer_list() throws IOException { assertEquals(2, historyPageFilter.queueItems.size()); assertEquals(3, historyPageFilter.runs.size()); - assertEquals(12, historyPageFilter.queueItems.get(0).getEntryId()); + assertEquals(12, historyPageFilter.queueItems.getFirst().getEntryId()); assertEquals(12, historyPageFilter.newestOnPage); - assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.runs.get(0).getEntryId()); + assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.runs.getFirst().getEntryId()); } /** @@ -285,7 +285,7 @@ void test_newerThan_doesntIncludeQueuedItems() throws IOException { assertEquals(0, historyPageFilter.queueItems.size()); assertEquals(5, historyPageFilter.runs.size()); - assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.runs.get(0).getEntryId()); + assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.runs.getFirst().getEntryId()); assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.newestOnPage); assertEquals(HistoryPageEntry.getEntryId(6), historyPageFilter.oldestOnPage); } @@ -328,7 +328,7 @@ void test_search_runs_by_build_number() throws IOException { //then assertEquals(1, historyPageFilter.runs.size()); - assertEquals(HistoryPageEntry.getEntryId(23), historyPageFilter.runs.get(0).getEntryId()); + assertEquals(HistoryPageEntry.getEntryId(23), historyPageFilter.runs.getFirst().getEntryId()); } @Test @@ -384,7 +384,7 @@ private void assertOneMatchingBuildForGivenSearchStringAndRunItems(String search //then assertEquals(1, historyPageFilter.runs.size()); - assertEquals(HistoryPageEntry.getEntryId(2), historyPageFilter.runs.get(0).getEntryId()); + assertEquals(HistoryPageEntry.getEntryId(2), historyPageFilter.runs.getFirst().getEntryId()); } private List newQueueItems(long startId, long endId) { diff --git a/test/src/test/java/hudson/ExtensionListTest.java b/test/src/test/java/hudson/ExtensionListTest.java index b62e2c3f0da6..94fd5a8803be 100644 --- a/test/src/test/java/hudson/ExtensionListTest.java +++ b/test/src/test/java/hudson/ExtensionListTest.java @@ -217,6 +217,6 @@ void removeAll(JenkinsRule j) { @Issue("JENKINS-62056") @Test void checkSort(JenkinsRule j) { - ExtensionList.lookup(Object.class).get(0); // exceptions are a problem + ExtensionList.lookup(Object.class).getFirst(); // exceptions are a problem } } diff --git a/test/src/test/java/hudson/PluginManagerInstalledGUITest.java b/test/src/test/java/hudson/PluginManagerInstalledGUITest.java index 7440e670b82d..97c826dbc79e 100644 --- a/test/src/test/java/hudson/PluginManagerInstalledGUITest.java +++ b/test/src/test/java/hudson/PluginManagerInstalledGUITest.java @@ -143,7 +143,7 @@ private InstalledPlugins(JenkinsRule jenkinsRule) throws IOException, SAXExcepti // able to see what the code is testing. DomElement pluginsTable = installedPage.getElementById("plugins"); - HtmlElement tbody = pluginsTable.getElementsByTagName("TBODY").get(0); + HtmlElement tbody = pluginsTable.getElementsByTagName("TBODY").getFirst(); installedPlugins = new ArrayList<>(); for (DomElement htmlTableRow : tbody.getChildElements()) { @@ -182,7 +182,7 @@ public boolean isPlugin(String pluginId) { } private HtmlInput getEnableWidget() { - HtmlElement input = pluginRow.getCells().get(hasHealth ? 2 : 1).getElementsByTagName("input").get(0); + HtmlElement input = pluginRow.getCells().get(hasHealth ? 2 : 1).getElementsByTagName("input").getFirst(); return (HtmlInput) input; } diff --git a/test/src/test/java/hudson/PluginManagerTest.java b/test/src/test/java/hudson/PluginManagerTest.java index 113e89915b70..8c8306b94d87 100644 --- a/test/src/test/java/hudson/PluginManagerTest.java +++ b/test/src/test/java/hudson/PluginManagerTest.java @@ -316,7 +316,7 @@ void prevalidateConfig() throws Throwable { assertNull(r.jenkins.getPluginManager().getPlugin("htmlpublisher")); List> jobs = r.jenkins.getPluginManager().prevalidateConfig(new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8))); assertEquals(1, jobs.size()); - UpdateCenterJob job = jobs.get(0).get(); // blocks for completion + UpdateCenterJob job = jobs.getFirst().get(); // blocks for completion assertEquals("InstallationJob", job.getType()); UpdateCenter.InstallationJob ijob = (UpdateCenter.InstallationJob) job; assertEquals("htmlpublisher", ijob.plugin.name); diff --git a/test/src/test/java/hudson/PluginTest.java b/test/src/test/java/hudson/PluginTest.java index 4228c8192a26..e522238003c8 100644 --- a/test/src/test/java/hudson/PluginTest.java +++ b/test/src/test/java/hudson/PluginTest.java @@ -75,7 +75,7 @@ void doDynamic() throws Exception { @Issue("SECURITY-925") void preventTimestamp2_toBeServed() throws Exception { // impossible to use installDetachedPlugin("credentials") since we want to have it exploded like with WAR - Jenkins.get().getUpdateCenter().getSites().get(0).updateDirectlyNow(false); + Jenkins.get().getUpdateCenter().getSites().getFirst().updateDirectlyNow(false); List> pluginInstalled = r.jenkins.pluginManager.install(List.of("credentials"), true); for (Future job : pluginInstalled) { diff --git a/test/src/test/java/hudson/cli/ReloadConfigurationCommandTest.java b/test/src/test/java/hudson/cli/ReloadConfigurationCommandTest.java index bfc4b0ffd80e..7e5dc5376529 100644 --- a/test/src/test/java/hudson/cli/ReloadConfigurationCommandTest.java +++ b/test/src/test/java/hudson/cli/ReloadConfigurationCommandTest.java @@ -168,7 +168,7 @@ void reloadViewConfig() throws Exception { @Disabled // Until fixed JENKINS-8217 @Test void reloadDescriptorConfig() { - Mailer.DescriptorImpl desc = j.jenkins.getExtensionList(Mailer.DescriptorImpl.class).get(0); + Mailer.DescriptorImpl desc = j.jenkins.getExtensionList(Mailer.DescriptorImpl.class).getFirst(); desc.setDefaultSuffix("@oldSuffix"); desc.save(); diff --git a/test/src/test/java/hudson/core/PluginManagerOverrideTest.java b/test/src/test/java/hudson/core/PluginManagerOverrideTest.java index bf8d55ec50bf..1f93e92ade27 100644 --- a/test/src/test/java/hudson/core/PluginManagerOverrideTest.java +++ b/test/src/test/java/hudson/core/PluginManagerOverrideTest.java @@ -30,7 +30,7 @@ void setUp(JenkinsRule rule) { void testViewOverrides() throws Exception { // Verify extension registered correctly and comes back in overrides assertEquals(1, PluginManagerStaplerOverride.all().size()); - assertThat(PluginManagerStaplerOverride.all().get(0), instanceOf(BasicPluginManagerOverride.class)); + assertThat(PluginManagerStaplerOverride.all().getFirst(), instanceOf(BasicPluginManagerOverride.class)); // Verify we can load untouched resources JenkinsRule.WebClient client = j.createWebClient(); diff --git a/test/src/test/java/hudson/init/InitMilestoneTest.java b/test/src/test/java/hudson/init/InitMilestoneTest.java index bac3690d9378..21e2b0c6cbac 100644 --- a/test/src/test/java/hudson/init/InitMilestoneTest.java +++ b/test/src/test/java/hudson/init/InitMilestoneTest.java @@ -26,7 +26,7 @@ void setUp(JenkinsRule rule) { @Test void testInitMilestones() { - List attained = r.jenkins.getExtensionList(Initializers.class).get(0).getAttained(); + List attained = r.jenkins.getExtensionList(Initializers.class).getFirst().getAttained(); // TODO assert that they are contained in order, currently it generally works but flakes after some time assertThat(attained, containsInAnyOrder( diff --git a/test/src/test/java/hudson/model/AbstractProjectTest.java b/test/src/test/java/hudson/model/AbstractProjectTest.java index 1e8612af3cd4..3ac99f014699 100644 --- a/test/src/test/java/hudson/model/AbstractProjectTest.java +++ b/test/src/test/java/hudson/model/AbstractProjectTest.java @@ -389,7 +389,7 @@ void queueSuccessBehaviorOverHTTP() throws Exception { void vectorTriggers() throws Exception { AbstractProject p = (AbstractProject) j.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("AbstractProjectTest/vectorTriggers.xml")); assertEquals(1, p.triggers().size()); - Trigger t = p.triggers().get(0); + Trigger t = p.triggers().getFirst(); assertEquals(SCMTrigger.class, t.getClass()); assertEquals("*/10 * * * *", t.getSpec()); } @@ -413,7 +413,7 @@ void addTriggerSameType() throws Exception { p.addTrigger(newTrigger); assertEquals(1, p.triggers().size()); - Trigger t = p.triggers().get(0); + Trigger t = p.triggers().getFirst(); assertEquals(SCMTrigger.class, t.getClass()); assertEquals("H/5 * * * *", t.getSpec()); } diff --git a/test/src/test/java/hudson/model/CauseTest.java b/test/src/test/java/hudson/model/CauseTest.java index 0382bc24a6ec..f4abfe9a19ba 100644 --- a/test/src/test/java/hudson/model/CauseTest.java +++ b/test/src/test/java/hudson/model/CauseTest.java @@ -42,6 +42,7 @@ import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import jenkins.model.Jenkins; @@ -304,11 +305,7 @@ public void setVirtualName(String virtualName) { @NonNull @Override public String getName() { - if (virtualName != null) { - return virtualName; - } else { - return super.getName(); - } + return Objects.requireNonNullElseGet(virtualName, super::getName); } @Override diff --git a/test/src/test/java/hudson/model/ComputerTest.java b/test/src/test/java/hudson/model/ComputerTest.java index aef59d8bf344..5d99347f4123 100644 --- a/test/src/test/java/hudson/model/ComputerTest.java +++ b/test/src/test/java/hudson/model/ComputerTest.java @@ -333,7 +333,7 @@ public void isConnectedTest() throws Exception { // Connect the computer computer.connect(false); - await("computer should be online after connect").atMost(Duration.ofSeconds(30)).until(() -> computer.isOnline(), is(true)); + await("computer should be online after connect").atMost(Duration.ofSeconds(30)).until(computer::isOnline, is(true)); assertThat(computer.isConnected(), is(true)); assertThat(computer.isOffline(), is(false)); @@ -351,7 +351,7 @@ public void isConnectedTest() throws Exception { // Disconnect the computer computer.disconnect(new OfflineCause.UserCause(null, null)); // wait for the slave process to be killed - await("disconnected agent is not available for scheduling").until(() -> computer.isOnline(), is(false)); + await("disconnected agent is not available for scheduling").until(computer::isOnline, is(false)); assertThat(computer.isConnected(), is(false)); assertThat(computer.isOffline(), is(true)); } diff --git a/test/src/test/java/hudson/model/DescriptorTest.java b/test/src/test/java/hudson/model/DescriptorTest.java index aa4822125d59..eb9f13cfea41 100644 --- a/test/src/test/java/hudson/model/DescriptorTest.java +++ b/test/src/test/java/hudson/model/DescriptorTest.java @@ -83,15 +83,15 @@ void overriddenId() throws Exception { rule.configRoundtrip(p); List builders = p.getBuildersList(); assertEquals(1, builders.size()); - assertEquals(BuilderImpl.class, builders.get(0).getClass()); - assertEquals("builder-a", ((BuilderImpl) builders.get(0)).id); + assertEquals(BuilderImpl.class, builders.getFirst().getClass()); + assertEquals("builder-a", ((BuilderImpl) builders.getFirst()).id); rule.assertLogContains("running builder-a", rule.buildAndAssertSuccess(p)); p.getBuildersList().replace(new BuilderImpl("builder-b")); rule.configRoundtrip(p); builders = p.getBuildersList(); assertEquals(1, builders.size()); - assertEquals(BuilderImpl.class, builders.get(0).getClass()); - assertEquals("builder-b", ((BuilderImpl) builders.get(0)).id); + assertEquals(BuilderImpl.class, builders.getFirst().getClass()); + assertEquals("builder-b", ((BuilderImpl) builders.getFirst()).id); rule.assertLogContains("running builder-b", rule.buildAndAssertSuccess(p)); } diff --git a/test/src/test/java/hudson/model/ExecutorTest.java b/test/src/test/java/hudson/model/ExecutorTest.java index e0c665a02896..5fec54721b95 100644 --- a/test/src/test/java/hudson/model/ExecutorTest.java +++ b/test/src/test/java/hudson/model/ExecutorTest.java @@ -100,7 +100,7 @@ void abortCause() throws Exception { j.assertBuildStatus(Result.FAILURE, j.waitForCompletion(b)); InterruptedBuildAction iba = b.getAction(InterruptedBuildAction.class); assertEquals(1, iba.getCauses().size()); - assertEquals(((UserInterruption) iba.getCauses().get(0)).getUser(), johnny); + assertEquals(((UserInterruption) iba.getCauses().getFirst()).getUser(), johnny); // make sure it shows up in the log j.assertLogContains(johnny.getId(), b); diff --git a/test/src/test/java/hudson/model/FingerprintTest.java b/test/src/test/java/hudson/model/FingerprintTest.java index c05710a76bc0..5be179da0d16 100644 --- a/test/src/test/java/hudson/model/FingerprintTest.java +++ b/test/src/test/java/hudson/model/FingerprintTest.java @@ -119,7 +119,7 @@ void roundTrip() throws Exception { f2 = Fingerprint.load(SOME_MD5); assertEquals(f.toString(), f2.toString()); assertEquals(1, f2.facets.size()); - TestFacet facet = (TestFacet) f2.facets.get(0); + TestFacet facet = (TestFacet) f2.facets.getFirst(); assertEquals(f2, facet.getFingerprint()); } @@ -224,13 +224,13 @@ void shouldBeUnableToSeeJobsIfNoPermissions() throws Exception { assertEquals(project1.getName(), original.getName(), "user1 should be able to see the origin's project name"); assertEquals(build.getNumber(), original.getNumber(), "user1 should be able to see the origin's build number"); assertEquals(1, fp._getUsages().size(), "Only one usage should be visible to user1"); - assertEquals(project1.getFullName(), fp._getUsages().get(0).name, "Only project1 should be visible to user1"); + assertEquals(project1.getFullName(), fp._getUsages().getFirst().name, "Only project1 should be visible to user1"); } try (ACLContext acl = ACL.as(user2)) { assertThat("user2 should be unable to see the origin", fp.getOriginal(), nullValue()); assertEquals(1, fp._getUsages().size(), "Only one usage should be visible to user2"); - assertEquals(project2.getFullName(), fp._getUsages().get(0).name, "Only project2 should be visible to user2"); + assertEquals(project2.getFullName(), fp._getUsages().getFirst().name, "Only project2 should be visible to user2"); } try (ACLContext acl = ACL.as(user3)) { diff --git a/test/src/test/java/hudson/model/FreeStyleProjectTest.java b/test/src/test/java/hudson/model/FreeStyleProjectTest.java index d82433301fc6..2792995ad2fd 100644 --- a/test/src/test/java/hudson/model/FreeStyleProjectTest.java +++ b/test/src/test/java/hudson/model/FreeStyleProjectTest.java @@ -100,9 +100,9 @@ void configSubmission() throws Exception { List builders = project.getBuilders(); assertEquals(1, builders.size()); - assertEquals(Shell.class, builders.get(0).getClass()); - assertEquals("echo hello", ((Shell) builders.get(0)).getCommand().trim()); - assertNotSame(builders.get(0), shell); + assertEquals(Shell.class, builders.getFirst().getClass()); + assertEquals("echo hello", ((Shell) builders.getFirst()).getCommand().trim()); + assertNotSame(builders.getFirst(), shell); } /** @@ -148,9 +148,9 @@ void minimalConfigXml() throws Exception { j.submit(form); List builders = project.getBuilders(); assertEquals(1, builders.size()); - assertEquals(Shell.class, builders.get(0).getClass()); - assertEquals("echo hello", ((Shell) builders.get(0)).getCommand().trim()); - assertNotSame(builders.get(0), shell); + assertEquals(Shell.class, builders.getFirst().getClass()); + assertEquals("echo hello", ((Shell) builders.getFirst()).getCommand().trim()); + assertNotSame(builders.getFirst(), shell); System.out.println(project.getConfigFile().asString()); } diff --git a/test/src/test/java/hudson/model/HelpLinkTest.java b/test/src/test/java/hudson/model/HelpLinkTest.java index a0c57e16cbd9..3a9a9d8a6b74 100644 --- a/test/src/test/java/hudson/model/HelpLinkTest.java +++ b/test/src/test/java/hudson/model/HelpLinkTest.java @@ -147,7 +147,7 @@ void negative() throws Exception { clickAllHelpLinks(webclient, p); statusListener.assertHasResponses(); - String contentAsString = statusListener.getResponses().get(0).getContentAsString(); + String contentAsString = statusListener.getResponses().getFirst().getContentAsString(); assertTrue(contentAsString.contains(d.getHelpFile())); } finally { Publisher.all().remove(d); diff --git a/test/src/test/java/hudson/model/JobTest.java b/test/src/test/java/hudson/model/JobTest.java index 192a73c3ec9b..9e7831f1a1d9 100644 --- a/test/src/test/java/hudson/model/JobTest.java +++ b/test/src/test/java/hudson/model/JobTest.java @@ -277,7 +277,7 @@ private static void tryConfigDotXml(JenkinsRule.WebClient wc, int status, String // This page is a simple form to POST to /job/testJob/config.xml // But it posts invalid data so we expect 500 if we have permission, 403 if not HtmlPage page = wc.goTo("userContent/post.html"); - p = HtmlFormUtil.submit(page.getForms().get(0)); + p = HtmlFormUtil.submit(page.getForms().getFirst()); assertEquals(status, p.getWebResponse().getStatusCode(), msg); p = wc.goTo("logout"); @@ -622,7 +622,7 @@ void getJobTabs() throws Exception { var response = project.getJobTabs(); assertThat(response, hasSize(1)); - assertThat(response.get(0).getDisplayName(), equalTo("Test")); + assertThat(response.getFirst().getDisplayName(), equalTo("Test")); } /** diff --git a/test/src/test/java/hudson/model/ListViewTest.java b/test/src/test/java/hudson/model/ListViewTest.java index 561562060c20..ef71996edca3 100644 --- a/test/src/test/java/hudson/model/ListViewTest.java +++ b/test/src/test/java/hudson/model/ListViewTest.java @@ -283,7 +283,7 @@ void addJobUsingAPI(TestInfo info) throws Exception { v.doCreateItem(req, rsp); List items = v.getItems(); assertEquals(1, items.size()); - assertEquals("job1", items.get(0).getName()); + assertEquals("job1", items.getFirst().getName()); } @Issue("JENKINS-23411") @@ -297,7 +297,7 @@ void doRemoveJobFromViewNullItem() throws Exception { List items = view.getItems(); assertEquals(1, items.size()); - assertEquals("job1", items.get(0).getName()); + assertEquals("job1", items.getFirst().getName()); // remove a contained job view.doRemoveJobFromView("job1"); diff --git a/test/src/test/java/hudson/model/MyViewsPropertyTest.java b/test/src/test/java/hudson/model/MyViewsPropertyTest.java index 5c8a66907646..4fc946e24b53 100644 --- a/test/src/test/java/hudson/model/MyViewsPropertyTest.java +++ b/test/src/test/java/hudson/model/MyViewsPropertyTest.java @@ -224,7 +224,7 @@ void testDoCreateView() throws Exception { user.addProperty(property); HtmlForm form = rule.createWebClient().goTo(property.getUrl() + "/newView").getFormByName("createItem"); form.getInputByName("name").setValue("foo"); - form.getRadioButtonsByName("mode").get(0).setChecked(true); + form.getRadioButtonsByName("mode").getFirst().setChecked(true); rule.submit(form); assertNotNull(property.getView("foo"), "Property should contain view foo"); } diff --git a/test/src/test/java/hudson/model/ParametersTest.java b/test/src/test/java/hudson/model/ParametersTest.java index 996bdc6460f4..48a435a1d49b 100644 --- a/test/src/test/java/hudson/model/ParametersTest.java +++ b/test/src/test/java/hudson/model/ParametersTest.java @@ -119,12 +119,12 @@ void choiceWithLTGT() throws Exception { HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec"); HtmlForm form = page.getFormByName("parameters"); - HtmlElement element = (HtmlElement) (form.getElementsByAttribute("input", "name", "name")).get(0).getParentNode(); + HtmlElement element = (HtmlElement) (form.getElementsByAttribute("input", "name", "name")).getFirst().getParentNode(); assertNotNull(element); assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(form, "//div[contains(@class, 'jenkins-form-description')]")).getTextContent()); assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(form, "//div[contains(@class, 'jenkins-form-label')]")).getTextContent()); - HtmlSelect choiceSelect = (HtmlSelect) form.getElementsByAttribute("select", "name", "value").get(0); + HtmlSelect choiceSelect = (HtmlSelect) form.getElementsByAttribute("select", "name", "value").getFirst(); HtmlOption opt = DomNodeUtil.selectSingleNode(choiceSelect, "option[@value='Choice <2>']"); assertNotNull(opt); diff --git a/test/src/test/java/hudson/model/ProjectTest.java b/test/src/test/java/hudson/model/ProjectTest.java index 6349d374fa57..176243a5e50d 100644 --- a/test/src/test/java/hudson/model/ProjectTest.java +++ b/test/src/test/java/hudson/model/ProjectTest.java @@ -279,7 +279,7 @@ void testGetScmCheckoutRetryCount() throws Exception { j.jenkins.setScmCheckoutRetryCount(6); assertEquals(6, p.getScmCheckoutRetryCount(), "Scm retry count should be the same as global scm retry count."); HtmlForm form = j.createWebClient().goTo(p.getUrl() + "/configure").getFormByName("config"); - ((HtmlElement) form.querySelectorAll(".advancedButton").get(0)).click(); + ((HtmlElement) form.querySelectorAll(".advancedButton").getFirst()).click(); // required due to the new default behavior of click form.getInputByName("hasCustomScmCheckoutRetryCount").click(new Event(), false, false, false, true); form.getInputByName("scmCheckoutRetryCount").setValue("7"); diff --git a/test/src/test/java/hudson/model/QueueTest.java b/test/src/test/java/hudson/model/QueueTest.java index fc7942e30794..0a94bd078b77 100644 --- a/test/src/test/java/hudson/model/QueueTest.java +++ b/test/src/test/java/hudson/model/QueueTest.java @@ -469,18 +469,14 @@ void tryWithTimeoutSuccessfullyAcquired() throws InterruptedException, Execution // Create a task that will need to wait until the first task is complete that will fail to acquire. final AtomicBoolean task2Result = new AtomicBoolean(false); - boolean acquired = Queue.tryWithLock(() -> { - task2Result.set(true); - }, Duration.ofMillis(10)); + boolean acquired = Queue.tryWithLock(() -> task2Result.set(true), Duration.ofMillis(10)); assertFalse(acquired); assertFalse(task2Result.get()); // Now release the first task and wait (with a long timeout) and we should succeed at getting the lock. final AtomicBoolean task3Result = new AtomicBoolean(false); task1Release.countDown(); - acquired = Queue.tryWithLock(() -> { - task3Result.set(true); - }, Duration.ofSeconds(30)); + acquired = Queue.tryWithLock(() -> task3Result.set(true), Duration.ofSeconds(30)); // First task should complete task1.get(); @@ -515,9 +511,7 @@ void tryWithTimeoutFailedToAcquire() throws InterruptedException, ExecutionExcep // Try to acquire lock with 50ms timeout, expecting that it cannot be acquired final AtomicBoolean task2Complete = new AtomicBoolean(false); - boolean result = Queue.tryWithLock(() -> { - task2Complete.set(true); - }, Duration.ofMillis(50)); + boolean result = Queue.tryWithLock(() -> task2Complete.set(true), Duration.ofMillis(50)); // Results should indicate the task did not run assertFalse(result); @@ -537,9 +531,7 @@ void tryWithTimeoutImmediatelyAcquired() throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); try { final AtomicBoolean taskComplete = new AtomicBoolean(false); - boolean result = Queue.tryWithLock(() -> { - taskComplete.set(true); - }, Duration.ofMillis(1)); + boolean result = Queue.tryWithLock(() -> taskComplete.set(true), Duration.ofMillis(1)); assertTrue(result); assertTrue(taskComplete.get()); } finally { @@ -1022,7 +1014,7 @@ public void save(){ project1.scheduleBuild2(0); QueueTaskFuture v = project2.scheduleBuild2(0); projectError.scheduleBuild2(0); - Executor e = r.jenkins.toComputer().getExecutors().get(0); + Executor e = r.jenkins.toComputer().getExecutors().getFirst(); Thread.sleep(2000); while (project2.getLastBuild() == null) { if (!e.isAlive()) { @@ -1188,7 +1180,7 @@ void queueApiOutputShouldBeFilteredByUserPermission() throws Exception { //james has DISCOVER permission on the project and will only be able to see the task name. List projects = p3.getByXPath("/queue/discoverableItem/task/name/text()"); assertEquals(1, projects.size()); - assertEquals("project", projects.get(0).toString()); + assertEquals("project", projects.getFirst().toString()); // Also check individual item exports. String url = project.getQueueItem().getUrl() + "api/xml"; @@ -1227,11 +1219,11 @@ void testGetCauseOfBlockageForNonConcurrentFreestyle() throws Exception { queue.maintain(); assertEquals(1, r.jenkins.getQueue().getBlockedItems().size()); - CauseOfBlockage actual = r.jenkins.getQueue().getBlockedItems().get(0).getCauseOfBlockage(); + CauseOfBlockage actual = r.jenkins.getQueue().getBlockedItems().getFirst().getCauseOfBlockage(); CauseOfBlockage expected = new BlockedBecauseOfBuildInProgress(t1.getFirstBuild()); assertEquals(expected.getShortDescription(), actual.getShortDescription()); - Queue.getInstance().doCancelItem(r.jenkins.getQueue().getBlockedItems().get(0).getId()); + Queue.getInstance().doCancelItem(r.jenkins.getQueue().getBlockedItems().getFirst().getId()); build.doStop(); // Stop build 1 early r.waitForCompletion(build); @@ -1533,7 +1525,7 @@ void computerFailsJustAfterCreatingExecutor() throws Throwable { var computer = onlineSlave.toComputer(); Timer.get().execute(() -> { // Simulate a computer failure just after the executor is created - while (computer.getExecutors().get(0).getStartTime() == 0) { + while (computer.getExecutors().getFirst().getStartTime() == 0) { try { Thread.sleep(10); } catch (InterruptedException e) { diff --git a/test/src/test/java/hudson/model/RunTest.java b/test/src/test/java/hudson/model/RunTest.java index 2564885b6138..8dd7aa2ce8b6 100644 --- a/test/src/test/java/hudson/model/RunTest.java +++ b/test/src/test/java/hudson/model/RunTest.java @@ -57,6 +57,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import jenkins.model.ArtifactManager; @@ -125,7 +126,7 @@ void getBadgeActions() throws Exception { b.keepLog(); List badgeActions = b.getBadgeActions(); assertEquals(1, badgeActions.size()); - assertEquals(Run.KeepLogBuildBadge.class, badgeActions.get(0).getClass()); + assertEquals(Run.KeepLogBuildBadge.class, badgeActions.getFirst().getClass()); } @Issue("JENKINS-51819") @@ -251,11 +252,7 @@ public void setVirtualName(String virtualName) { @NonNull @Override public String getName() { - if (virtualName != null) { - return virtualName; - } else { - return super.getName(); - } + return Objects.requireNonNullElseGet(virtualName, super::getName); } @Override @@ -361,7 +358,7 @@ public String getUrlName() { var response = run.getRunTabs(); assertThat(response, hasSize(1)); - assertThat(response.get(0).getDisplayName(), equalTo("Test")); + assertThat(response.getFirst().getDisplayName(), equalTo("Test")); } public static final class SlowMgr extends ArtifactManager { diff --git a/test/src/test/java/hudson/model/SlaveTest.java b/test/src/test/java/hudson/model/SlaveTest.java index 5974acc4bc1c..53f8a5ab418f 100644 --- a/test/src/test/java/hudson/model/SlaveTest.java +++ b/test/src/test/java/hudson/model/SlaveTest.java @@ -188,7 +188,7 @@ void launcherFiltering() { assumeTrue(descriptors.size() > 1, "we need at least two launchers to test this"); assertThat(descriptor.computerLauncherDescriptors(null), containsInAnyOrder(descriptors.toArray(new Descriptor[0]))); - Descriptor victim = descriptors.iterator().next(); + Descriptor victim = descriptors.getFirst(); assertThat(descriptor.computerLauncherDescriptors(null), hasItem(victim)); DynamicFilter.descriptors().add(victim); assertThat(descriptor.computerLauncherDescriptors(null), not(hasItem(victim))); @@ -205,7 +205,7 @@ void retentionFiltering() { assumeTrue(descriptors.size() > 1, "we need at least two retention strategies to test this"); assertThat(descriptor.retentionStrategyDescriptors(null), containsInAnyOrder(descriptors.toArray(new Descriptor[0]))); - Descriptor> victim = descriptors.iterator().next(); + Descriptor> victim = descriptors.getFirst(); assertThat(descriptor.retentionStrategyDescriptors(null), hasItem(victim)); DynamicFilter.descriptors().add(victim); assertThat(descriptor.retentionStrategyDescriptors(null), not(hasItem(victim))); @@ -223,7 +223,7 @@ void propertyFiltering() { assumeTrue(descriptors.size() > 1, "we need at least two node properties to test this"); assertThat(descriptor.nodePropertyDescriptors(null), containsInAnyOrder(descriptors.toArray(new Descriptor[0]))); - NodePropertyDescriptor victim = descriptors.iterator().next(); + NodePropertyDescriptor victim = descriptors.getFirst(); assertThat(descriptor.nodePropertyDescriptors(null), hasItem(victim)); DynamicFilter.descriptors().add(victim); assertThat(descriptor.nodePropertyDescriptors(null), not(hasItem(victim))); diff --git a/test/src/test/java/hudson/model/UpdateSiteTest.java b/test/src/test/java/hudson/model/UpdateSiteTest.java index 3c86c5a0ac59..0438b4f29980 100644 --- a/test/src/test/java/hudson/model/UpdateSiteTest.java +++ b/test/src/test/java/hudson/model/UpdateSiteTest.java @@ -202,9 +202,9 @@ void lackOfDataDoesNotFailWarningsCode() { assertNull(j.jenkins.getUpdateCenter().getSite("default").getData(), "plugin data is not present"); // nothing breaking? - j.jenkins.getExtensionList(UpdateSiteWarningsMonitor.class).get(0).getActivePluginWarningsByPlugin(); - j.jenkins.getExtensionList(UpdateSiteWarningsMonitor.class).get(0).getActiveCoreWarnings(); - j.jenkins.getExtensionList(UpdateSiteWarningsConfiguration.class).get(0).getAllWarnings(); + j.jenkins.getExtensionList(UpdateSiteWarningsMonitor.class).getFirst().getActivePluginWarningsByPlugin(); + j.jenkins.getExtensionList(UpdateSiteWarningsMonitor.class).getFirst().getActiveCoreWarnings(); + j.jenkins.getExtensionList(UpdateSiteWarningsConfiguration.class).getFirst().getAllWarnings(); } @Test diff --git a/test/src/test/java/hudson/model/UserTest.java b/test/src/test/java/hudson/model/UserTest.java index 062d22479c7f..cede8b2aa859 100644 --- a/test/src/test/java/hudson/model/UserTest.java +++ b/test/src/test/java/hudson/model/UserTest.java @@ -215,7 +215,7 @@ void testGetUser() throws Exception { User user3 = User.get("John Smith"); user3.setFullName("Alice Smith"); assertEquals("John Smith", user3.getId(), "What was this asserting exactly?"); - User user4 = User.get("Marie", false, Collections.EMPTY_MAP); + User user4 = User.get("Marie", false, Collections.emptyMap()); assertNull(user4, "User should not be created because Marie does not exists."); } } diff --git a/test/src/test/java/hudson/model/ViewTest.java b/test/src/test/java/hudson/model/ViewTest.java index 8cc90e3a9b53..a08f3858ee1e 100644 --- a/test/src/test/java/hudson/model/ViewTest.java +++ b/test/src/test/java/hudson/model/ViewTest.java @@ -175,7 +175,7 @@ void conflictingName() throws Exception { WebClient wc = j.createWebClient(); HtmlForm form = wc.goTo("newView").getFormByName("createItem"); form.getInputByName("name").setValue("foo"); - form.getRadioButtonsByName("mode").get(0).setChecked(true); + form.getRadioButtonsByName("mode").getFirst().setChecked(true); j.submit(form); assertNotNull(j.jenkins.getView("foo")); @@ -259,7 +259,7 @@ void notAllowedName() throws Exception { .withThrowExceptionOnFailingStatusCode(false); HtmlForm form = wc.goTo("newView").getFormByName("createItem"); form.getInputByName("name").setValue(".."); - form.getRadioButtonsByName("mode").get(0).setChecked(true); + form.getRadioButtonsByName("mode").getFirst().setChecked(true); HtmlPage page = j.submit(form); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, @@ -274,7 +274,7 @@ void unicodeName() throws Exception { HtmlForm form = j.createWebClient().goTo("newView").getFormByName("createItem"); String name = "I ♥ NY"; form.getInputByName("name").setValue(name); - form.getRadioButtonsByName("mode").get(0).setChecked(true); + form.getRadioButtonsByName("mode").getFirst().setChecked(true); j.submit(form); View view = j.jenkins.getView(name); assertNotNull(view); diff --git a/test/src/test/java/hudson/model/queue/LoadPredictorTest.java b/test/src/test/java/hudson/model/queue/LoadPredictorTest.java index b5fa1fe08c01..2c4316d9afaf 100644 --- a/test/src/test/java/hudson/model/queue/LoadPredictorTest.java +++ b/test/src/test/java/hudson/model/queue/LoadPredictorTest.java @@ -87,7 +87,7 @@ void test1() throws Exception { Computer c = createMockComputer(1); - JobOffer o = createMockOffer(c.getExecutors().get(0)); + JobOffer o = createMockOffer(c.getExecutors().getFirst()); MappingWorksheet mw = new MappingWorksheet(wrap(t), List.of(o)); diff --git a/test/src/test/java/hudson/model/queue/MaintainCanTakeStrengtheningTest.java b/test/src/test/java/hudson/model/queue/MaintainCanTakeStrengtheningTest.java index 99ebc20e0d2c..a8027346e05f 100644 --- a/test/src/test/java/hudson/model/queue/MaintainCanTakeStrengtheningTest.java +++ b/test/src/test/java/hudson/model/queue/MaintainCanTakeStrengtheningTest.java @@ -57,7 +57,7 @@ void testExceptionOnNodeProperty() throws Exception { // The faulty one is the only one in the queue assertThat(r.getInstance().getQueue().getBuildableItems().size(), equalTo(1)); - assertThat(r.getInstance().getQueue().getBuildableItems().get(0).task.getName(), equalTo("theFaultyOne")); + assertThat(r.getInstance().getQueue().getBuildableItems().getFirst().task.getName(), equalTo("theFaultyOne")); // The new error is shown in the logs assertThat(logging.getMessages(), hasItem(String.format("Exception evaluating if the node '%s' can take the task '%s'", faultyAgent.getDisplayName(), "theFaultyOne"))); diff --git a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java index e67cd78783bf..f767bc5a4f0b 100644 --- a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java +++ b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java @@ -281,14 +281,14 @@ void selfRegistrationTriggerLoggedIn() throws Exception { assertTrue(spySecurityListener.loggedInUsernames.isEmpty()); createFirstAccount("admin"); - assertEquals("admin", spySecurityListener.loggedInUsernames.get(0)); + assertEquals("admin", spySecurityListener.loggedInUsernames.getFirst()); createAccountByAdmin("alice"); // no new event in such case assertTrue(spySecurityListener.loggedInUsernames.isEmpty()); selfRegistration("bob"); - assertEquals("bob", spySecurityListener.loggedInUsernames.get(0)); + assertEquals("bob", spySecurityListener.loggedInUsernames.getFirst()); } @Issue("JENKINS-55307") @@ -339,7 +339,7 @@ void userCreationWithHashedPasswords() throws Exception { securityRealm.createAccountWithHashedPassword("charlie_hashed", "#jbcrypt:" + BCrypt.hashpw("charliePassword", BCrypt.gensalt())); - assertEquals("charlie_hashed", spySecurityListener.createdUsers.get(0)); + assertEquals("charlie_hashed", spySecurityListener.createdUsers.getFirst()); } private void createFirstAccount(String login) throws Exception { diff --git a/test/src/test/java/hudson/security/PermissionGroupTest.java b/test/src/test/java/hudson/security/PermissionGroupTest.java index ea28cd8586c1..b0d1b7f549eb 100644 --- a/test/src/test/java/hudson/security/PermissionGroupTest.java +++ b/test/src/test/java/hudson/security/PermissionGroupTest.java @@ -52,7 +52,7 @@ void setUp(JenkinsRule rule) { @Email("http://jenkins-ci.361315.n4.nabble.com/Master-slave-refactor-tp391495.html") @Test void order() { - assertSame(Jenkins.PERMISSIONS, PermissionGroup.getAll().get(0)); + assertSame(Jenkins.PERMISSIONS, PermissionGroup.getAll().getFirst()); } @SuppressWarnings("ResultOfObjectAllocationIgnored") diff --git a/test/src/test/java/hudson/slaves/NodeCanTakeTaskTest.java b/test/src/test/java/hudson/slaves/NodeCanTakeTaskTest.java index 0bc8cedcfa24..b950fd73c48f 100644 --- a/test/src/test/java/hudson/slaves/NodeCanTakeTaskTest.java +++ b/test/src/test/java/hudson/slaves/NodeCanTakeTaskTest.java @@ -76,7 +76,7 @@ void takeBlockedByProperty() throws Exception { assertNotNull(buildables); assertEquals(1, buildables.size()); - BuildableItem item = buildables.get(0); + BuildableItem item = buildables.getFirst(); assertEquals(project, item.task); assertNotNull(item.getCauseOfBlockage()); assertEquals("rejecting everything", item.getCauseOfBlockage().getShortDescription()); diff --git a/test/src/test/java/hudson/slaves/NodeProvisionerTest.java b/test/src/test/java/hudson/slaves/NodeProvisionerTest.java index e206e656f91c..dd998ee3f2a3 100644 --- a/test/src/test/java/hudson/slaves/NodeProvisionerTest.java +++ b/test/src/test/java/hudson/slaves/NodeProvisionerTest.java @@ -263,7 +263,7 @@ private static void _flyweightTasksWithoutMasterExecutors(JenkinsRule r) throws assertEquals("", build.getBuiltOnStr()); List runs = build.getRuns(); assertEquals(1, runs.size()); - assertEquals("slave0", runs.get(0).getBuiltOnStr()); + assertEquals("slave0", runs.getFirst().getBuiltOnStr()); } /** diff --git a/test/src/test/java/hudson/tasks/ArtifactArchiverTest.java b/test/src/test/java/hudson/tasks/ArtifactArchiverTest.java index e355fa607234..0c35eb18b40f 100644 --- a/test/src/test/java/hudson/tasks/ArtifactArchiverTest.java +++ b/test/src/test/java/hudson/tasks/ArtifactArchiverTest.java @@ -220,7 +220,7 @@ void symlinks() throws Exception { assumeTrue(ws.child("dir/lodge").exists(), "May not be testable on Windows:\n" + JenkinsRule.getLog(b)); List artifacts = b.getArtifacts(); assertEquals(1, artifacts.size()); - FreeStyleBuild.Artifact artifact = artifacts.get(0); + FreeStyleBuild.Artifact artifact = artifacts.getFirst(); assertEquals("dir/lodge", artifact.relativePath); VirtualFile[] kids = b.getArtifactManager().root().child("dir").list(); assertEquals(1, kids.length); @@ -296,7 +296,7 @@ void outsideSymlinks() throws Exception { FreeStyleBuild b = j.buildAndAssertSuccess(p); List artifacts = b.getArtifacts(); assertEquals(1, artifacts.size()); - FreeStyleBuild.Artifact artifact = artifacts.get(0); + FreeStyleBuild.Artifact artifact = artifacts.getFirst(); assertEquals("hack", artifact.relativePath); VirtualFile[] kids = b.getArtifactManager().root().list(); assertEquals(1, kids.length); @@ -545,7 +545,7 @@ void lengthOfArtifactIsCorrect_eventForInvalidSymlink() throws Exception { artifacts.sort(Comparator.comparing(Run.Artifact::getFileName)); // invalid symlink => size of 0 - FreeStyleBuild.Artifact artifact = artifacts.get(0); + FreeStyleBuild.Artifact artifact = artifacts.getFirst(); assertEquals("dir/_nonexistant", artifact.relativePath); assertEquals(0, artifact.getFileSize()); assertEquals("", artifact.getLength()); diff --git a/test/src/test/java/hudson/tasks/BatchFileTest.java b/test/src/test/java/hudson/tasks/BatchFileTest.java index fe919ac36d1f..d5d9f30007ae 100644 --- a/test/src/test/java/hudson/tasks/BatchFileTest.java +++ b/test/src/test/java/hudson/tasks/BatchFileTest.java @@ -158,7 +158,7 @@ void windowsUnstableCodeZeroIsSameAsUnset() { @LocalData void canLoadUnstableReturnFromDisk() { FreeStyleProject p = (FreeStyleProject) rule.jenkins.getItemByFullName("batch"); - BatchFile batchFile = (BatchFile) p.getBuildersList().get(0); + BatchFile batchFile = (BatchFile) p.getBuildersList().getFirst(); assertEquals((Integer) 1, batchFile.getUnstableReturn(), "unstable return"); } } diff --git a/test/src/test/java/hudson/tasks/CommandInterpreterTest.java b/test/src/test/java/hudson/tasks/CommandInterpreterTest.java index a1401e350983..e52b594795b2 100644 --- a/test/src/test/java/hudson/tasks/CommandInterpreterTest.java +++ b/test/src/test/java/hudson/tasks/CommandInterpreterTest.java @@ -30,7 +30,7 @@ void setUp(JenkinsRule rule) { @Test @LocalData void ensurePluginCommandInterpretersCanBeLoaded() { - final Builder builder = j.jenkins.getItemByFullName("a", FreeStyleProject.class).getBuildersList().get(0); + final Builder builder = j.jenkins.getItemByFullName("a", FreeStyleProject.class).getBuildersList().getFirst(); assertThat(builder, instanceOf(TestCommandInterpreter.class)); assertDoesNotThrow(() -> { diff --git a/test/src/test/java/hudson/tasks/FingerprinterTest.java b/test/src/test/java/hudson/tasks/FingerprinterTest.java index 2b4a259e2a09..01f9e76fcab8 100644 --- a/test/src/test/java/hudson/tasks/FingerprinterTest.java +++ b/test/src/test/java/hudson/tasks/FingerprinterTest.java @@ -244,7 +244,7 @@ void matrixDependency() throws Exception { RunList builds = freestyleProject.getBuilds(); assertEquals(1, builds.size(), "There should only be one FreestyleBuild"); - FreeStyleBuild build = builds.iterator().next(); + FreeStyleBuild build = builds.getFirst(); assertEquals(Result.SUCCESS, build.getResult()); List downstream = j.jenkins.getDependencyGraph().getDownstream(matrixProject); assertTrue(downstream.contains(freestyleProject)); diff --git a/test/src/test/java/hudson/tasks/ShellTest.java b/test/src/test/java/hudson/tasks/ShellTest.java index 48f8fe875cdb..561b6c35376f 100644 --- a/test/src/test/java/hudson/tasks/ShellTest.java +++ b/test/src/test/java/hudson/tasks/ShellTest.java @@ -195,7 +195,7 @@ void unixUnstableCodeZeroIsSameAsUnset() { @LocalData void canLoadUnstableReturnFromDisk() { FreeStyleProject p = (FreeStyleProject) rule.jenkins.getItemByFullName("test"); - Shell shell = (Shell) p.getBuildersList().get(0); + Shell shell = (Shell) p.getBuildersList().getFirst(); assertEquals((Integer) 1, shell.getUnstableReturn(), "unstable return"); } diff --git a/test/src/test/java/hudson/tools/ToolLocationNodePropertyTest.java b/test/src/test/java/hudson/tools/ToolLocationNodePropertyTest.java index c19073d4b7a9..fadf7d338f24 100644 --- a/test/src/test/java/hudson/tools/ToolLocationNodePropertyTest.java +++ b/test/src/test/java/hudson/tools/ToolLocationNodePropertyTest.java @@ -97,7 +97,7 @@ void formRoundTrip() throws Exception { ToolLocationNodeProperty prop = slave.getNodeProperties().get(ToolLocationNodeProperty.class); assertEquals(3, prop.getLocations().size()); - ToolLocationNodeProperty.ToolLocation location = prop.getLocations().get(0); + ToolLocationNodeProperty.ToolLocation location = prop.getLocations().getFirst(); assertEquals(jdkDescriptor, location.getType()); assertEquals("jdk", location.getName()); assertEquals("foobar", location.getHome()); diff --git a/test/src/test/java/hudson/util/FormFieldValidatorTest.java b/test/src/test/java/hudson/util/FormFieldValidatorTest.java index 1a2f4bc9c83e..8dd6a4d34940 100644 --- a/test/src/test/java/hudson/util/FormFieldValidatorTest.java +++ b/test/src/test/java/hudson/util/FormFieldValidatorTest.java @@ -162,7 +162,7 @@ void negative() throws Exception { webclient.getPage(p, "configure"); statusListener.assertHasResponses(); - String contentAsString = statusListener.getResponses().get(0).getContentAsString(); + String contentAsString = statusListener.getResponses().getFirst().getContentAsString(); assertTrue(contentAsString.contains("doCheckXyz is broken")); } finally { Publisher.all().remove(d); diff --git a/test/src/test/java/hudson/util/SecretCompatTest.java b/test/src/test/java/hudson/util/SecretCompatTest.java index 6833a371d5bb..6f3e934354fc 100644 --- a/test/src/test/java/hudson/util/SecretCompatTest.java +++ b/test/src/test/java/hudson/util/SecretCompatTest.java @@ -93,7 +93,7 @@ void canReadPreSec304Secrets() throws Exception { //It should be unchanged on disk assertThat(oldxml, containsString("z/Dd3qrHdQ6/C5lR7uEafM/jD3nQDrGprw3XsfZ/0vo=")); ParametersDefinitionProperty property = project.getProperty(ParametersDefinitionProperty.class); - ParameterDefinition definition = property.getParameterDefinitions().get(0); + ParameterDefinition definition = property.getParameterDefinitions().getFirst(); assertThat(definition, instanceOf(PasswordParameterDefinition.class)); Secret secret = ((PasswordParameterDefinition) definition).getDefaultValueAsSecret(); assertEquals("theSecret", secret.getPlainText()); diff --git a/test/src/test/java/jenkins/cli/DefaultCLIListenerTest.java b/test/src/test/java/jenkins/cli/DefaultCLIListenerTest.java index 5091f52b61a6..bfa2993dcb47 100644 --- a/test/src/test/java/jenkins/cli/DefaultCLIListenerTest.java +++ b/test/src/test/java/jenkins/cli/DefaultCLIListenerTest.java @@ -95,7 +95,7 @@ void commandOnThrowableIsLogged() { messages.get(1), containsString("Failed call to CLI command list-jobs, with 1 arguments, as user %s.".formatted(USER))); assertThat( - logging.getRecords().get(0).getThrown().getMessage(), + logging.getRecords().getFirst().getThrown().getMessage(), containsString("No view or item group with the given name 'view-not-found' found")); } @@ -113,7 +113,7 @@ void commandOnThrowableUnexpectedIsLogged() { assertThat( messages.get(1), containsString("Unexpected exception occurred while performing throws-test-command command.")); - assertThat(logging.getRecords().get(0).getThrown().getMessage(), containsString("unexpected")); + assertThat(logging.getRecords().getFirst().getThrown().getMessage(), containsString("unexpected")); } @Test @@ -147,7 +147,7 @@ void methodOnThrowableIsLogged() { containsString( "Failed call to CLI command disable-job, with 1 arguments, as user %s.".formatted(USER))); assertThat( - logging.getRecords().get(0).getThrown().getMessage(), + logging.getRecords().getFirst().getThrown().getMessage(), containsString("No such job ‘job-not-found’ exists.")); } @@ -162,7 +162,7 @@ void methodOnThrowableUnexpectedIsLogged() { messages.get(0), containsString("Invoking CLI command restart, with 0 arguments, as user %s.".formatted(USER))); assertThat(messages.get(1), containsString("Unexpected exception occurred while performing restart command.")); - assertThat(logging.getRecords().get(0).getThrown(), notNullValue()); + assertThat(logging.getRecords().getFirst().getThrown(), notNullValue()); } @TestExtension diff --git a/test/src/test/java/jenkins/install/InstallUtilTest.java b/test/src/test/java/jenkins/install/InstallUtilTest.java index 44b611524299..13180c1cac52 100644 --- a/test/src/test/java/jenkins/install/InstallUtilTest.java +++ b/test/src/test/java/jenkins/install/InstallUtilTest.java @@ -165,16 +165,12 @@ void testSaveAndRestoreInstallingPlugins() { String statusType = name.split(":")[1]; name = name.split(":")[0]; - InstallationStatus status; - if ("Success".equals(statusType)) { - status = Mockito.mock(Success.class, Mockito.CALLS_REAL_METHODS); - } else if ("Failure".equals(statusType)) { - status = Mockito.mock(Failure.class, Mockito.CALLS_REAL_METHODS); - } else if ("Installing".equals(statusType)) { - status = Mockito.mock(Installing.class, Mockito.CALLS_REAL_METHODS); - } else { - status = Mockito.mock(Pending.class, Mockito.CALLS_REAL_METHODS); - } + InstallationStatus status = switch (statusType) { + case "Success" -> Mockito.mock(Success.class, Mockito.CALLS_REAL_METHODS); + case "Failure" -> Mockito.mock(Failure.class, Mockito.CALLS_REAL_METHODS); + case "Installing" -> Mockito.mock(Installing.class, Mockito.CALLS_REAL_METHODS); + case null, default -> Mockito.mock(Pending.class, Mockito.CALLS_REAL_METHODS); + }; nameMap.put(statusType, status.getClass().getSimpleName()); diff --git a/test/src/test/java/jenkins/install/SetupWizardTest.java b/test/src/test/java/jenkins/install/SetupWizardTest.java index 96d7be182014..39919259b139 100644 --- a/test/src/test/java/jenkins/install/SetupWizardTest.java +++ b/test/src/test/java/jenkins/install/SetupWizardTest.java @@ -102,7 +102,7 @@ void tearDown() { private void wizardLogin(JenkinsRule.WebClient wc) throws Exception { HtmlPage page = wc.goTo("login"); - HtmlForm form = page.getForms().get(0); + HtmlForm form = page.getForms().getFirst(); form.getInputByName("j_password").setValue(initialAdminPassword); HtmlFormUtil.submit(form, null); } diff --git a/test/src/test/java/jenkins/model/GlobalComputerRetentionCheckIntervalConfigurationTest.java b/test/src/test/java/jenkins/model/GlobalComputerRetentionCheckIntervalConfigurationTest.java index 5e55886833ec..e6f79a0a53ec 100644 --- a/test/src/test/java/jenkins/model/GlobalComputerRetentionCheckIntervalConfigurationTest.java +++ b/test/src/test/java/jenkins/model/GlobalComputerRetentionCheckIntervalConfigurationTest.java @@ -67,7 +67,7 @@ private void checkUsesFallbackAfterLoadOf(int interval) throws IOException { c.load(); assertEquals(60, c.getComputerRetentionCheckInterval(), "uses default"); assertEquals(1, logging.getRecords().size(), "prints one fallback message"); - assertEquals("computerRetentionCheckInterval must be greater than zero, falling back to 60s", logging.getRecords().get(0).getMessage(), "fallback message content"); + assertEquals("computerRetentionCheckInterval must be greater than zero, falling back to 60s", logging.getRecords().getFirst().getMessage(), "fallback message content"); } @Test @@ -98,7 +98,7 @@ void bootWithTooLargeValue() throws IOException { c.load(); assertEquals(60, c.getComputerRetentionCheckInterval(), "uses default"); assertEquals(1, logging.getRecords().size(), "prints one fallback message"); - assertEquals("computerRetentionCheckInterval is limited to 60s", logging.getRecords().get(0).getMessage(), "fallback message content"); + assertEquals("computerRetentionCheckInterval is limited to 60s", logging.getRecords().getFirst().getMessage(), "fallback message content"); } @Test diff --git a/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java b/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java index 712527b0b65c..ad3f893fa8d1 100644 --- a/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java +++ b/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java @@ -288,18 +288,18 @@ void externalBuildDirectoryRenameDelete() throws Throwable { story.then(steps -> { builds.add(newFolder(tmp, "junit").toString()); assertTrue(steps.getInstance().isDefaultBuildDir()); - setBuildsDirProperty(builds.get(0) + "/${ITEM_FULL_NAME}"); + setBuildsDirProperty(builds.getFirst() + "/${ITEM_FULL_NAME}"); }); story.then(steps -> { - assertEquals(builds.get(0) + "/${ITEM_FULL_NAME}", steps.jenkins.getRawBuildsDir()); + assertEquals(builds.getFirst() + "/${ITEM_FULL_NAME}", steps.jenkins.getRawBuildsDir()); FreeStyleProject p = steps.jenkins.createProject(MockFolder.class, "d").createProject(FreeStyleProject.class, "prj"); FreeStyleBuild b = p.scheduleBuild2(0).get(); - File oldBuildDir = new File(builds.get(0), "d/prj"); + File oldBuildDir = new File(builds.getFirst(), "d/prj"); assertEquals(new File(oldBuildDir, b.getId()), b.getRootDir()); assertTrue(b.getRootDir().isDirectory()); p.renameTo("proj"); - File newBuildDir = new File(builds.get(0), "d/proj"); + File newBuildDir = new File(builds.getFirst(), "d/proj"); assertEquals(new File(newBuildDir, b.getId()), b.getRootDir()); assertTrue(b.getRootDir().isDirectory()); p.delete(); diff --git a/test/src/test/java/jenkins/model/JenkinsReloadConfigurationTest.java b/test/src/test/java/jenkins/model/JenkinsReloadConfigurationTest.java index 574df44ecc57..7639293f7a65 100644 --- a/test/src/test/java/jenkins/model/JenkinsReloadConfigurationTest.java +++ b/test/src/test/java/jenkins/model/JenkinsReloadConfigurationTest.java @@ -142,7 +142,7 @@ void loadExecutorsConfig() throws Exception { } private Mailer.DescriptorImpl mailerDescriptor() { - return j.jenkins.getExtensionList(Mailer.DescriptorImpl.class).get(0); + return j.jenkins.getExtensionList(Mailer.DescriptorImpl.class).getFirst(); } private void replace(String path, String search, String replace) { diff --git a/test/src/test/java/jenkins/model/JenkinsTest.java b/test/src/test/java/jenkins/model/JenkinsTest.java index 6705323ad077..c2847e779be3 100644 --- a/test/src/test/java/jenkins/model/JenkinsTest.java +++ b/test/src/test/java/jenkins/model/JenkinsTest.java @@ -153,7 +153,7 @@ void verifyUploadedFingerprintFilePermission() throws Exception { assumeFalse(Functions.isWindows()); HtmlPage page = j.createWebClient().goTo("fingerprintCheck"); - HtmlForm form = page.getForms().get(0); + HtmlForm form = page.getForms().getFirst(); File dir = newFolder(tmp, "junit"); File plugin = new File(dir, "htmlpublisher.jpi"); // We're using a plugin to have a file above DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD diff --git a/test/src/test/java/jenkins/model/ScriptListenerTest.java b/test/src/test/java/jenkins/model/ScriptListenerTest.java index a8b6eb8b3f10..6acd1ccfe53c 100644 --- a/test/src/test/java/jenkins/model/ScriptListenerTest.java +++ b/test/src/test/java/jenkins/model/ScriptListenerTest.java @@ -57,7 +57,7 @@ void consoleUsageIsLogged() throws IOException { final List messages = logging.getMessages(); assertThat(messages, hasSize(2)); - assertThat(messages.get(0), containsString("Execution of script: '" + script + "' with binding: '[:]' in feature: 'class hudson.util.RemotingDiagnostics' and context: 'hudson.remoting.LocalChannel@")); + assertThat(messages.getFirst(), containsString("Execution of script: '" + script + "' with binding: '[:]' in feature: 'class hudson.util.RemotingDiagnostics' and context: 'hudson.remoting.LocalChannel@")); assertThat(messages.get(0), containsString("' with correlation: '")); assertThat(messages.get(0), containsString("' (no user)")); @@ -92,7 +92,7 @@ void groovyCliUsageIsLogged() { final List messages = logging.getMessages(); assertThat(messages, hasSize(3)); - assertThat(messages.get(0), containsString("Execution of script: '" + script + "' with binding: '[")); + assertThat(messages.getFirst(), containsString("Execution of script: '" + script + "' with binding: '[")); assertThat(messages.get(0), containsString("]' in feature: 'class hudson.cli.GroovyCommand' and context: 'null' with correlation: '")); assertThat(messages.get(0), containsString("' (no user)")); diff --git a/test/src/test/java/jenkins/security/Security1166Test.java b/test/src/test/java/jenkins/security/Security1166Test.java index 59308cdebc72..4512e66e3b2b 100644 --- a/test/src/test/java/jenkins/security/Security1166Test.java +++ b/test/src/test/java/jenkins/security/Security1166Test.java @@ -185,7 +185,7 @@ void loginThroughSetupWizard() throws Exception { try (JenkinsRule.WebClient wc = j.createWebClient().withThrowExceptionOnFailingStatusCode(false)) { HtmlPage page = wc.goTo("login"); List forms = page.getForms(); - HtmlForm form = forms.get(0); + HtmlForm form = forms.getFirst(); assertEquals(1, forms.size()); // It's the only form, which doesn't have a name or an id. diff --git a/test/src/test/java/jenkins/security/SpySecurityListener.java b/test/src/test/java/jenkins/security/SpySecurityListener.java index 31028f808e23..af85c6cdfeee 100644 --- a/test/src/test/java/jenkins/security/SpySecurityListener.java +++ b/test/src/test/java/jenkins/security/SpySecurityListener.java @@ -98,7 +98,7 @@ public void assertLastEventIsAndThenRemoveIt(Predicate predicate) { fail("event list is empty"); } - T t = eventList.remove(eventList.size() - 1); + T t = eventList.removeLast(); assertTrue(predicate.test(t)); eventList.clear(); } diff --git a/test/src/test/java/jenkins/security/stapler/PreventRoutingTest.java b/test/src/test/java/jenkins/security/stapler/PreventRoutingTest.java index 0dc8a7959c30..d8c2b52c5842 100644 --- a/test/src/test/java/jenkins/security/stapler/PreventRoutingTest.java +++ b/test/src/test/java/jenkins/security/stapler/PreventRoutingTest.java @@ -110,7 +110,7 @@ private static void notStaplerGetter(@NonNull Object o) { StaplerRequest2 req = Stapler.getCurrentRequest2(); if (req != null) { List ancestors = req.getAncestors(); - if (!ancestors.isEmpty() && ancestors.get(ancestors.size() - 1).getObject() == o) { + if (!ancestors.isEmpty() && ancestors.getLast().getObject() == o) { throw HttpResponses.notFound(); } } diff --git a/test/src/test/java/jenkins/security/stapler/StaplerDispatchValidatorTest.java b/test/src/test/java/jenkins/security/stapler/StaplerDispatchValidatorTest.java index f121e9347852..983c43e67746 100644 --- a/test/src/test/java/jenkins/security/stapler/StaplerDispatchValidatorTest.java +++ b/test/src/test/java/jenkins/security/stapler/StaplerDispatchValidatorTest.java @@ -80,7 +80,7 @@ void canViewRoot() throws Exception { String[] urls = {"annotated/root", "groovy/root", "jelly/root", "whitelist/root"}; for (String url : urls) { HtmlPage root = j.createWebClient().goTo(url); - assertEquals("Fragment", root.getElementById("frag").getChildNodes().get(0).getNodeValue()); + assertEquals("Fragment", root.getElementById("frag").getChildNodes().getFirst().getNodeValue()); } } diff --git a/test/src/test/java/jenkins/widgets/HistoryPageFilterCaseSensitiveSearchTest.java b/test/src/test/java/jenkins/widgets/HistoryPageFilterCaseSensitiveSearchTest.java index 48a55af81e8c..1f2643520369 100644 --- a/test/src/test/java/jenkins/widgets/HistoryPageFilterCaseSensitiveSearchTest.java +++ b/test/src/test/java/jenkins/widgets/HistoryPageFilterCaseSensitiveSearchTest.java @@ -45,7 +45,7 @@ void setUp(JenkinsRule rule) { void should_search_case_sensitively_when_enabled_for_user() throws IOException { setCaseSensitiveSearchForUserAndCheckAssertionForGivenSearchString("FAILURE", historyPageFilter -> { assertEquals(1, historyPageFilter.runs.size()); - assertEquals(HistoryPageEntry.getEntryId(2), historyPageFilter.runs.get(0).getEntryId()); + assertEquals(HistoryPageEntry.getEntryId(2), historyPageFilter.runs.getFirst().getEntryId()); }); } diff --git a/test/src/test/java/lib/form/ExpandableTextboxTest.java b/test/src/test/java/lib/form/ExpandableTextboxTest.java index f6f8a4019930..5053e81adbbb 100644 --- a/test/src/test/java/lib/form/ExpandableTextboxTest.java +++ b/test/src/test/java/lib/form/ExpandableTextboxTest.java @@ -130,7 +130,7 @@ private void checkInjectionInName(TestRootAction testParams) throws Exception { private HtmlButton getExpandButton(HtmlPage page) { DomNodeList buttons = page.getElementById("test-panel").getElementsByTagName("button"); assertEquals(1, buttons.size()); - return (HtmlButton) buttons.get(0); + return (HtmlButton) buttons.getFirst(); } @TestExtension("noInjectionArePossible") diff --git a/test/src/test/java/lib/form/OptionTest.java b/test/src/test/java/lib/form/OptionTest.java index 8ecf4af665c4..449a57bc089c 100644 --- a/test/src/test/java/lib/form/OptionTest.java +++ b/test/src/test/java/lib/form/OptionTest.java @@ -291,7 +291,7 @@ private void callPageAndCheckIfResultContainsExpected(String url, String bodyCon DomNodeList elements = document.getElementsByTagName("option"); assertEquals(1, elements.size()); - HtmlOption option = (HtmlOption) elements.get(0); + HtmlOption option = (HtmlOption) elements.getFirst(); // without that check, the getValue could return getText if the value is not present assertNotEquals(DomElement.ATTRIBUTE_NOT_DEFINED, option.getAttribute("value")); diff --git a/test/src/test/java/lib/form/PasswordTest.java b/test/src/test/java/lib/form/PasswordTest.java index 88a69e2e7867..6e75d4475984 100644 --- a/test/src/test/java/lib/form/PasswordTest.java +++ b/test/src/test/java/lib/form/PasswordTest.java @@ -581,7 +581,7 @@ void testBuildStep() throws Exception { j.configRoundtrip(project); // empty default values after initial form submission - PasswordHolderBuildStep buildStep = (PasswordHolderBuildStep) project.getBuildersList().get(0); + PasswordHolderBuildStep buildStep = (PasswordHolderBuildStep) project.getBuildersList().getFirst(); assertNotNull(buildStep); assertEquals("", buildStep.secretWithSecretGetterSecretSetter.getPlainText()); assertEquals("", buildStep.secretWithSecretGetterStringSetter.getPlainText()); @@ -592,7 +592,7 @@ void testBuildStep() throws Exception { assertEquals("", buildStep.stringWithStringGetterSecretSetter); assertEquals("", buildStep.stringWithStringGetterStringSetter); - buildStep = (PasswordHolderBuildStep) project.getBuildersList().get(0); + buildStep = (PasswordHolderBuildStep) project.getBuildersList().getFirst(); assertNotNull(buildStep); @@ -634,7 +634,7 @@ void testBuildStep() throws Exception { assertTrue(i >= 8); // at least 8 password fields expected on that job config form j.configRoundtrip(project); - buildStep = (PasswordHolderBuildStep) project.getBuildersList().get(0); + buildStep = (PasswordHolderBuildStep) project.getBuildersList().getFirst(); // confirm round-trip did not change effective values assertEquals("secretWithSecretGetterSecretSetter", buildStep.secretWithSecretGetterSecretSetter.getPlainText()); @@ -787,7 +787,7 @@ void testStringlyTypedSecrets() throws Exception { j.configRoundtrip(project); // empty default values after initial form submission - StringlyTypedSecretsBuilder buildStep = (StringlyTypedSecretsBuilder) project.getBuildersList().get(0); + StringlyTypedSecretsBuilder buildStep = (StringlyTypedSecretsBuilder) project.getBuildersList().getFirst(); assertNotNull(buildStep); assertTrue(buildStep.mySecret.startsWith("{")); assertTrue(buildStep.mySecret.endsWith("}")); @@ -811,7 +811,7 @@ void testStringlyTypedSecrets() throws Exception { } j.configRoundtrip(project); - buildStep = (StringlyTypedSecretsBuilder) project.getBuildersList().get(0); + buildStep = (StringlyTypedSecretsBuilder) project.getBuildersList().getFirst(); // confirm round-trip did not change effective values assertEquals("stringlyTypedSecret", Secret.fromString(buildStep.mySecret).getPlainText()); diff --git a/test/src/test/java/lib/form/RepeatableTest.java b/test/src/test/java/lib/form/RepeatableTest.java index fd9df536dc34..1b3442f6ad9e 100644 --- a/test/src/test/java/lib/form/RepeatableTest.java +++ b/test/src/test/java/lib/form/RepeatableTest.java @@ -634,7 +634,7 @@ private void assertEqualsJsonArray(String golden, Object jsonArray) { private static HtmlButton getHtmlButton(HtmlForm form, String buttonCaption, boolean isTopButton) { List buttons = getButtonsList(form, buttonCaption); if (buttons.size() == 1) { - return (HtmlButton) buttons.get(0); + return (HtmlButton) buttons.getFirst(); } return (HtmlButton) buttons.get(isTopButton ? 0 : 1); } diff --git a/test/src/test/java/lib/form/RowVisibilityGroupTest.java b/test/src/test/java/lib/form/RowVisibilityGroupTest.java index 3ba4bb1202e7..6aa4f09bd0f3 100644 --- a/test/src/test/java/lib/form/RowVisibilityGroupTest.java +++ b/test/src/test/java/lib/form/RowVisibilityGroupTest.java @@ -105,17 +105,17 @@ void test2() throws Exception { // reveal the text box List checkboxes = DomNodeUtil.selectNodes(p, "//INPUT[@name='inner']"); assertEquals(2, checkboxes.size()); - checkboxes.get(0).click(); - assertTrue(textboxes.get(0).isDisplayed()); - textboxes.get(0).type("Budweiser"); + checkboxes.getFirst().click(); + assertTrue(textboxes.getFirst().isDisplayed()); + textboxes.getFirst().type("Budweiser"); // toggle the selection again s.setSelectedAttribute(opts.get(1), true); s.setSelectedAttribute(opts.get(0), true); // make sure it's still displayed this time - assertTrue(checkboxes.get(0).isChecked()); - assertTrue(textboxes.get(0).isDisplayed()); + assertTrue(checkboxes.getFirst().isChecked()); + assertTrue(textboxes.getFirst().isDisplayed()); // make sure we get what we expect j.submit(p.getFormByName("config")); diff --git a/test/src/test/java/lib/form/ValidateButtonTest.java b/test/src/test/java/lib/form/ValidateButtonTest.java index 9ac2793c6139..b080787d599c 100644 --- a/test/src/test/java/lib/form/ValidateButtonTest.java +++ b/test/src/test/java/lib/form/ValidateButtonTest.java @@ -189,7 +189,7 @@ private void checkInjectionInWith(NoInjectionArePossible.DescriptorImpl descript private HtmlButton getValidateButton(HtmlPage page) { DomNodeList buttons = page.getElementById("test-panel").getElementsByTagName("button"); assertEquals(1, buttons.size()); - return (HtmlButton) buttons.get(0); + return (HtmlButton) buttons.getFirst(); } @TestExtension("noInjectionArePossible") diff --git a/test/src/test/java/lib/layout/ConfirmationLinkTest.java b/test/src/test/java/lib/layout/ConfirmationLinkTest.java index c2c001b0e7c6..c8fc97839892 100644 --- a/test/src/test/java/lib/layout/ConfirmationLinkTest.java +++ b/test/src/test/java/lib/layout/ConfirmationLinkTest.java @@ -179,7 +179,7 @@ private HtmlButton getClickableLink(HtmlPage page) throws IOException { HtmlElement document = page.getDocumentElement(); DomNodeList anchors = page.getElementById("test-panel").getElementsByTagName("a"); assertEquals(1, anchors.size()); - HtmlAnchor anchor = (HtmlAnchor) anchors.get(0); + HtmlAnchor anchor = (HtmlAnchor) anchors.getFirst(); HtmlElementUtil.click(anchor); HtmlButton revokeButtonSelected = document.getOneHtmlElementByAttribute("button", "data-id", "ok"); return revokeButtonSelected; diff --git a/test/src/test/java/lib/layout/IconTest.java b/test/src/test/java/lib/layout/IconTest.java index 7b63effb32f5..f540c3809fa5 100644 --- a/test/src/test/java/lib/layout/IconTest.java +++ b/test/src/test/java/lib/layout/IconTest.java @@ -99,7 +99,7 @@ void testBallColorTd() throws Exception { DomElement ballColorAborted = p.getElementById("ballColorAborted"); assertThat("Aborted", is(ballColorAborted.getTextContent())); - HtmlElement symbol = ballColorAborted.getElementsByTagName("svg").get(0); + HtmlElement symbol = ballColorAborted.getElementsByTagName("svg").getFirst(); assertThat("icon-md", is(symbol.getAttribute("class"))); assertIconToSymbolOkay(symbol); @@ -149,17 +149,17 @@ void testTasks() throws Exception { DomElement tasksDiv = p.getElementById("tasks"); List taskDivs = StreamSupport.stream(tasksDiv.getChildElements().spliterator(), false).toList(); - assertIconToSymbolOkay(taskDivs.get(0).getElementsByTagName("svg").get(0)); + assertIconToSymbolOkay(taskDivs.get(0).getElementsByTagName("svg").getFirst()); // this is loading the png from cloudbees-folder plugin // when this is swapped to an SVG and the dep updated this test will need to change - assertIconToSvgOkay(taskDivs.get(1).getElementsByTagName("svg").get(0), "icon-folder icon-md"); - assertIconToImageOkay(taskDivs.get(2).getElementsByTagName("img").get(0), "/images/svgs/package.svg"); - assertIconToImageOkay(taskDivs.get(3).getElementsByTagName("img").get(0), "/images/svgs/package.svg"); - assertIconToImageOkay(taskDivs.get(4).getElementsByTagName("img").get(0), "/images/svgs/package.svg"); - assertIconToSymbolOkay(taskDivs.get(5).getElementsByTagName("svg").get(0)); - - assertIconToImageOkay(taskDivs.get(6).getElementsByTagName("img").get(0), "/plugin/xxx/icon.png"); - assertIconToImageOkay(taskDivs.get(7).getElementsByTagName("img").get(0), "/plugin/xxx/icon.png"); + assertIconToSvgOkay(taskDivs.get(1).getElementsByTagName("svg").getFirst(), "icon-folder icon-md"); + assertIconToImageOkay(taskDivs.get(2).getElementsByTagName("img").getFirst(), "/images/svgs/package.svg"); + assertIconToImageOkay(taskDivs.get(3).getElementsByTagName("img").getFirst(), "/images/svgs/package.svg"); + assertIconToImageOkay(taskDivs.get(4).getElementsByTagName("img").getFirst(), "/images/svgs/package.svg"); + assertIconToSymbolOkay(taskDivs.get(5).getElementsByTagName("svg").getFirst()); + + assertIconToImageOkay(taskDivs.get(6).getElementsByTagName("img").getFirst(), "/plugin/xxx/icon.png"); + assertIconToImageOkay(taskDivs.get(7).getElementsByTagName("img").getFirst(), "/plugin/xxx/icon.png"); } @TestExtension("testTasks") diff --git a/test/src/test/java/lib/layout/StopButtonTest.java b/test/src/test/java/lib/layout/StopButtonTest.java index 39ddc21b666d..4dc514e72b17 100644 --- a/test/src/test/java/lib/layout/StopButtonTest.java +++ b/test/src/test/java/lib/layout/StopButtonTest.java @@ -124,7 +124,7 @@ private void checkInjectionInConfirm(TestRootAction testParams) throws Exception private HtmlAnchor getStopLink(HtmlPage page) { DomNodeList anchors = page.getElementById("test-panel").getElementsByTagName("a"); assertEquals(1, anchors.size()); - return (HtmlAnchor) anchors.get(0); + return (HtmlAnchor) anchors.getFirst(); } @TestExtension("noInjectionArePossible") diff --git a/war/src/main/java/executable/Main.java b/war/src/main/java/executable/Main.java index 70411a635218..61ae4449308b 100644 --- a/war/src/main/java/executable/Main.java +++ b/war/src/main/java/executable/Main.java @@ -46,6 +46,7 @@ import java.util.List; import java.util.MissingResourceException; import java.util.NavigableSet; +import java.util.Objects; import java.util.TreeSet; import java.util.UUID; import java.util.jar.JarFile; @@ -317,13 +318,9 @@ public static void main(String[] args) throws IllegalAccessException { try { Field f = cl.loadClass("winstone.WinstoneSession").getField("SESSION_COOKIE_NAME"); f.setAccessible(true); - if (JSESSIONID_COOKIE_NAME != null) { - // Use the user-defined cookie name - f.set(null, JSESSIONID_COOKIE_NAME); - } else { - // Randomize session names by default to prevent collisions when running multiple Jenkins instances on the same host. - f.set(null, "JSESSIONID." + UUID.randomUUID().toString().replace("-", "").substring(0, 8)); - } + // Use the user-defined cookie name or + // randomized session names as default to prevent collisions when running multiple Jenkins instances on the same host. + f.set(null, Objects.requireNonNullElseGet(JSESSIONID_COOKIE_NAME, () -> "JSESSIONID." + UUID.randomUUID().toString().replace("-", "").substring(0, 8))); } catch (ClassNotFoundException | NoSuchFieldException e) { throw new AssertionError(e); }