Skip to content

Commit 4a2f5f2

Browse files
Migrate code base to Java 21 (#26075)
* Replace if-cascades with switch * Reference to empty collection field replaced with method call (Java 5) * Anonymous type replaced with lambda (Java 8) * Replaced lambda with method reference (Java 8) * Statement lambda replaced with expression lambda (Java 8) * Loop replaced with 'Collection.removeIf()' (Java 8) * Null check replaced with method call (Java 9) * Statement replaced with enhanced 'switch' (Java 14) * Use text blocks (Java 15) * Use pattern variable (Java 16) * Replace if-cascades with switch * Use 'Comparator' combinator * Null check replaced with method call (Java 9) * Use pattern variable (Java 16) * Use record pattern (Java 21) * Use SequencedCollection method (Java 21) * Replaced lambda with method reference (Java 8) * Cleanup unused imports * Cleanup migrations (move comments, formatting, spotbugs...) * Remove duplicate comment Resolve GitHub Copilot review comment * Remove blank line that may confuse Copilot * Inject comments into source line Attempt to satisfy GitHub Copilot Complains about unreachable code * Simplify with return value of switch statement * Use pattern matching instanceof in one more case * Don't lose the NetBeans comment that was there before * Remove TODO for Java 21 pattern use, implemented * Align comments with Unicode character they describe --------- Co-authored-by: Mark Waite <mark.earl.waite@gmail.com>
1 parent ee64d99 commit 4a2f5f2

File tree

194 files changed

+1008
-1362
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

194 files changed

+1008
-1362
lines changed

cli/src/main/java/hudson/cli/CLI.java

Lines changed: 35 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -138,40 +138,45 @@ public static int _main(String[] _args) throws Exception {
138138

139139
while (!args.isEmpty()) {
140140
String head = args.get(0);
141-
if (head.equals("-version")) {
142-
System.out.println("Version: " + computeVersion());
143-
return 0;
144-
}
145-
if (head.equals("-http")) {
146-
if (mode != null) {
147-
printUsage("-http clashes with previously defined mode " + mode);
148-
return -1;
141+
switch (head) {
142+
case "-version" -> {
143+
System.out.println("Version: " + computeVersion());
144+
return 0;
149145
}
150-
mode = Mode.HTTP;
151-
args = args.subList(1, args.size());
152-
continue;
153-
}
154-
if (head.equals("-ssh")) {
155-
if (mode != null) {
156-
printUsage("-ssh clashes with previously defined mode " + mode);
157-
return -1;
146+
case "-http" -> {
147+
if (mode != null) {
148+
printUsage("-http clashes with previously defined mode " + mode);
149+
return -1;
150+
}
151+
mode = Mode.HTTP;
152+
args = args.subList(1, args.size());
153+
continue;
158154
}
159-
mode = Mode.SSH;
160-
args = args.subList(1, args.size());
161-
continue;
162-
}
163-
if (head.equals("-webSocket")) {
164-
if (mode != null) {
165-
printUsage("-webSocket clashes with previously defined mode " + mode);
155+
case "-ssh" -> {
156+
if (mode != null) {
157+
printUsage("-ssh clashes with previously defined mode " + mode);
158+
return -1;
159+
}
160+
mode = Mode.SSH;
161+
args = args.subList(1, args.size());
162+
continue;
163+
}
164+
case "-webSocket" -> {
165+
if (mode != null) {
166+
printUsage("-webSocket clashes with previously defined mode " + mode);
167+
return -1;
168+
}
169+
mode = Mode.WEB_SOCKET;
170+
args = args.subList(1, args.size());
171+
continue;
172+
}
173+
case "-remoting" -> {
174+
printUsage("-remoting mode is no longer supported");
166175
return -1;
167176
}
168-
mode = Mode.WEB_SOCKET;
169-
args = args.subList(1, args.size());
170-
continue;
171-
}
172-
if (head.equals("-remoting")) {
173-
printUsage("-remoting mode is no longer supported");
174-
return -1;
177+
default -> {
178+
// continue
179+
}
175180
}
176181
if (head.equals("-s") && args.size() >= 2) {
177182
url = args.get(1);

cli/src/main/java/hudson/cli/PlainCLIProtocol.java

Lines changed: 42 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -262,28 +262,33 @@ abstract static class ServerSide extends EitherSide {
262262
@Override
263263
protected final boolean handle(Op op, DataInputStream dis) throws IOException {
264264
assert op.clientSide;
265-
switch (op) {
266-
case ARG:
267-
onArg(dis.readUTF());
268-
return true;
269-
case LOCALE:
270-
onLocale(dis.readUTF());
271-
return true;
272-
case ENCODING:
273-
onEncoding(dis.readUTF());
274-
return true;
275-
case START:
276-
onStart();
277-
return true;
278-
case STDIN:
279-
onStdin(dis.readAllBytes());
280-
return true;
281-
case END_STDIN:
282-
onEndStdin();
283-
return true;
284-
default:
285-
return false;
286-
}
265+
return switch (op) {
266+
case ARG -> {
267+
onArg(dis.readUTF());
268+
yield true;
269+
}
270+
case LOCALE -> {
271+
onLocale(dis.readUTF());
272+
yield true;
273+
}
274+
case ENCODING -> {
275+
onEncoding(dis.readUTF());
276+
yield true;
277+
}
278+
case START -> {
279+
onStart();
280+
yield true;
281+
}
282+
case STDIN -> {
283+
onStdin(dis.readAllBytes());
284+
yield true;
285+
}
286+
case END_STDIN -> {
287+
onEndStdin();
288+
yield true;
289+
}
290+
default -> false;
291+
};
287292
}
288293

289294
protected abstract void onArg(String text);
@@ -321,19 +326,21 @@ abstract static class ClientSide extends EitherSide {
321326
@Override
322327
protected boolean handle(Op op, DataInputStream dis) throws IOException {
323328
assert !op.clientSide;
324-
switch (op) {
325-
case EXIT:
326-
onExit(dis.readInt());
327-
return true;
328-
case STDOUT:
329-
onStdout(dis.readAllBytes());
330-
return true;
331-
case STDERR:
332-
onStderr(dis.readAllBytes());
333-
return true;
334-
default:
335-
return false;
336-
}
329+
return switch (op) {
330+
case EXIT -> {
331+
onExit(dis.readInt());
332+
yield true;
333+
}
334+
case STDOUT -> {
335+
onStdout(dis.readAllBytes());
336+
yield true;
337+
}
338+
case STDERR -> {
339+
onStderr(dis.readAllBytes());
340+
yield true;
341+
}
342+
default -> false;
343+
};
337344
}
338345

339346
protected abstract void onExit(int code);

cli/src/main/java/hudson/cli/SSHCLI.java

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,10 @@
2929
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
3030
import hudson.util.QuotedStringTokenizer;
3131
import java.io.IOException;
32-
import java.net.SocketAddress;
3332
import java.net.SocketTimeoutException;
3433
import java.net.URL;
3534
import java.net.URLConnection;
3635
import java.security.KeyPair;
37-
import java.security.PublicKey;
3836
import java.util.List;
3937
import java.util.Set;
4038
import java.util.logging.Level;
@@ -45,7 +43,6 @@
4543
import org.apache.sshd.client.future.ConnectFuture;
4644
import org.apache.sshd.client.keyverifier.DefaultKnownHostsServerKeyVerifier;
4745
import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier;
48-
import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
4946
import org.apache.sshd.client.session.ClientSession;
5047
import org.apache.sshd.common.future.WaitableFuture;
5148
import org.apache.sshd.common.util.io.input.NoCloseInputStream;
@@ -86,12 +83,9 @@ static int sshConnection(String jenkinsUrl, String user, List<String> args, Priv
8683

8784
try (SshClient client = SshClient.setUpDefaultClient()) {
8885

89-
KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier(new ServerKeyVerifier() {
90-
@Override
91-
public boolean verifyServerKey(ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey) {
92-
CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString());
93-
return !strictHostKey;
94-
}
86+
KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier((clientSession, remoteAddress, serverKey) -> {
87+
CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString());
88+
return !strictHostKey;
9589
}, true);
9690

9791
client.setServerKeyVerifier(verifier);

core/src/main/java/hudson/EnvVars.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ private void cutCycle(List<String> cycle) {
282282
}
283283

284284
// if not, cut the reference to the first one.
285-
cutCycleAt(cycle.get(0), cycle);
285+
cutCycleAt(cycle.getFirst(), cycle);
286286
}
287287

288288
/**

core/src/main/java/hudson/ExtensionFinder.java

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,7 @@ public <T> void onProvision(ProvisionInvocation<T> provision) {
628628
.flatMap(Collection::stream)
629629
.filter(m -> m.getAnnotation(PostConstruct.class) != null || m.getAnnotation(javax.annotation.PostConstruct.class) != null)
630630
.findFirst()
631-
.ifPresent(method -> methods.add(0, method));
631+
.ifPresent(methods::addFirst);
632632
c = c.getSuperclass();
633633
}
634634

@@ -788,16 +788,12 @@ private Level logLevel(IndexItem<Extension, Object> item) {
788788

789789
private static Class<?> getClassFromIndex(IndexItem<Extension, Object> item) throws InstantiationException {
790790
AnnotatedElement e = item.element();
791-
Class<?> extType;
792-
if (e instanceof Class) {
793-
extType = (Class) e;
794-
} else if (e instanceof Field) {
795-
extType = ((Field) e).getType();
796-
} else if (e instanceof Method) {
797-
extType = ((Method) e).getReturnType();
798-
} else {
799-
throw new AssertionError();
800-
}
791+
Class<?> extType = switch (e) {
792+
case Class aClass -> aClass;
793+
case Field field -> field.getType();
794+
case Method method -> method.getReturnType();
795+
case null, default -> throw new AssertionError();
796+
};
801797
return extType;
802798
}
803799

core/src/main/java/hudson/ExtensionList.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,7 @@ public static <T> ExtensionList<T> create(Jenkins jenkins, Class<T> type) {
457457
} else if (all.size() != 1) {
458458
throw new IllegalStateException("Expected 1 instance of " + type.getName() + " but got " + all.size());
459459
}
460-
return all.get(0);
460+
return all.getFirst();
461461
}
462462

463463
/**
@@ -474,7 +474,7 @@ public static <T> ExtensionList<T> create(Jenkins jenkins, Class<T> type) {
474474
public static @NonNull <U> U lookupFirst(Class<U> type) {
475475
var all = lookup(type);
476476
if (!all.isEmpty()) {
477-
return all.get(0);
477+
return all.getFirst();
478478
} else {
479479
if (Main.isUnitTest) {
480480
throw new IllegalStateException("Found no instances of " + type.getName() +

core/src/main/java/hudson/FilePath.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -350,15 +350,15 @@ public static String normalize(@NonNull String path) {
350350
if (i == 0) {
351351
// If absolute path, just remove: /../something
352352
// If relative path, not collapsible so leave as-is
353-
tokens.remove(0);
354-
if (!tokens.isEmpty()) token += tokens.remove(0);
353+
tokens.removeFirst();
354+
if (!tokens.isEmpty()) token += tokens.removeFirst();
355355
if (!isAbsolute) buf.append(token);
356356
} else {
357357
// Normalize: remove something/.. plus separator before/after
358358
i -= 2;
359359
for (int j = 0; j < 3; j++) tokens.remove(i);
360360
if (i > 0) tokens.remove(i - 1);
361-
else if (!tokens.isEmpty()) tokens.remove(0);
361+
else if (!tokens.isEmpty()) tokens.removeFirst();
362362
}
363363
} else
364364
i += 2;

core/src/main/java/hudson/Functions.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@
142142
import java.util.List;
143143
import java.util.Locale;
144144
import java.util.Map;
145+
import java.util.Objects;
145146
import java.util.Optional;
146147
import java.util.Set;
147148
import java.util.SortedMap;
@@ -1278,11 +1279,7 @@ public static boolean hasAnyPermission(Object object, Permission[] permissions)
12781279
return hasAnyPermission((AccessControlled) object, permissions);
12791280
else {
12801281
AccessControlled ac = Stapler.getCurrentRequest2().findAncestorObject(AccessControlled.class);
1281-
if (ac != null) {
1282-
return hasAnyPermission(ac, permissions);
1283-
}
1284-
1285-
return hasAnyPermission(Jenkins.get(), permissions);
1282+
return hasAnyPermission(Objects.requireNonNullElseGet(ac, Jenkins::get), permissions);
12861283
}
12871284
}
12881285

core/src/main/java/hudson/MarkupText.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ public void addMarkup(int startPos, int endPos, String startTag, String endTag)
266266
// <b><i>abc</i></b>, not <b><i>abc</b></i>. Also, we'd like <b>abc</b><i>def</i>,
267267
// not <b>abc<i></b>def</i>. Do this by inserting them to different places.
268268
tags.add(new Tag(startPos, startTag));
269-
tags.add(0, new Tag(endPos, endTag));
269+
tags.addFirst(new Tag(endPos, endTag));
270270
}
271271

272272
public void addMarkup(int pos, String tag) {

0 commit comments

Comments
 (0)