Skip to content

Commit 6d17999

Browse files
authored
Use Java 11 methods where possible (#6700)
1 parent 1a6d9f0 commit 6d17999

File tree

148 files changed

+419
-527
lines changed

Some content is hidden

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

148 files changed

+419
-527
lines changed

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

+2-3
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@
4747
import java.security.KeyPair;
4848
import java.security.SecureRandom;
4949
import java.util.Arrays;
50-
import java.util.Collections;
5150
import java.util.List;
5251
import java.util.Locale;
5352
import java.util.Map;
@@ -267,7 +266,7 @@ public boolean verify(String s, SSLSession sslSession) {
267266
}
268267

269268
if (args.isEmpty())
270-
args = Collections.singletonList("help"); // default to help
269+
args = List.of("help"); // default to help
271270

272271
if (mode == null) {
273272
mode = Mode.HTTP;
@@ -346,7 +345,7 @@ class Authenticator extends ClientEndpointConfig.Configurator {
346345
@Override
347346
public void beforeRequest(Map<String, List<String>> headers) {
348347
if (factory.authorization != null) {
349-
headers.put("Authorization", Collections.singletonList(factory.authorization));
348+
headers.put("Authorization", List.of(factory.authorization));
350349
}
351350
}
352351
}

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

+1-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
import java.net.URLConnection;
3636
import java.security.KeyPair;
3737
import java.security.PublicKey;
38-
import java.util.Collections;
3938
import java.util.List;
4039
import java.util.Set;
4140
import java.util.logging.Level;
@@ -114,7 +113,7 @@ public boolean verifyServerKey(ClientSession clientSession, SocketAddress remote
114113
WaitableFuture wf = channel.open();
115114
wf.await();
116115

117-
Set<ClientChannelEvent> waitMask = channel.waitFor(Collections.singletonList(ClientChannelEvent.CLOSED), 0L);
116+
Set<ClientChannelEvent> waitMask = channel.waitFor(List.of(ClientChannelEvent.CLOSED), 0L);
118117

119118
if (waitMask.contains(ClientChannelEvent.TIMEOUT)) {
120119
throw new SocketTimeoutException("Failed to retrieve command result in time: " + command);

cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,9 @@ void newop() throws IOException {
157157
while (server.stdin.size() == 0) {
158158
Thread.sleep(100);
159159
}
160-
assertEquals("hello", server.stdin.toString(Charset.defaultCharset().name()));
160+
assertEquals("hello", server.stdin.toString(Charset.defaultCharset()));
161161
assertEquals("command", server.arg);
162-
assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset().name()));
162+
assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset()));
163163
assertEquals(2, client.code);
164164
}
165165

core/src/main/java/hudson/ClassicPluginStrategy.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
import java.util.Enumeration;
5151
import java.util.HashSet;
5252
import java.util.List;
53+
import java.util.Set;
5354
import java.util.jar.Attributes;
5455
import java.util.jar.JarFile;
5556
import java.util.jar.Manifest;
@@ -338,7 +339,7 @@ public <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson huds
338339
List<ExtensionFinder> finders;
339340
if (type == ExtensionFinder.class) {
340341
// Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders
341-
finders = Collections.singletonList(new ExtensionFinder.Sezpoz());
342+
finders = List.of(new ExtensionFinder.Sezpoz());
342343
} else {
343344
finders = hudson.getExtensionList(ExtensionFinder.class);
344345
}
@@ -597,7 +598,7 @@ static final class DependencyClassLoader extends ClassLoader {
597598
DependencyClassLoader(ClassLoader parent, File archive, List<Dependency> dependencies, PluginManager pluginManager) {
598599
super(parent);
599600
this._for = archive;
600-
this.dependencies = Collections.unmodifiableList(new ArrayList<>(dependencies));
601+
this.dependencies = List.copyOf(dependencies);
601602
this.pluginManager = pluginManager;
602603
}
603604

@@ -629,7 +630,7 @@ protected List<PluginWrapper> getEdges(PluginWrapper pw) {
629630
for (Dependency d : dependencies) {
630631
PluginWrapper p = pluginManager.getPlugin(d.shortName);
631632
if (p != null && p.isActive())
632-
cgd.run(Collections.singleton(p));
633+
cgd.run(Set.of(p));
633634
}
634635
} catch (CycleDetectedException e) {
635636
throw new AssertionError(e); // such error should have been reported earlier

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -560,7 +560,7 @@ protected void configure() {
560560
}
561561

562562
public List<IndexItem<?, Object>> getLoadedIndex() {
563-
return Collections.unmodifiableList(new ArrayList<>(loadedIndex));
563+
return List.copyOf(loadedIndex);
564564
}
565565

566566
@Override
@@ -645,7 +645,7 @@ private List<IndexItem<Extension, Object>> getIndices() {
645645
// 5. dead lock
646646
if (indices == null) {
647647
ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader;
648-
indices = Collections.unmodifiableList(StreamSupport.stream(Index.load(Extension.class, Object.class, cl).spliterator(), false).collect(Collectors.toList()));
648+
indices = StreamSupport.stream(Index.load(Extension.class, Object.class, cl).spliterator(), false).collect(Collectors.toUnmodifiableList());
649649
}
650650
return indices;
651651
}

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -2382,7 +2382,7 @@ private static class ReadToString extends MasterToSlaveFileCallable<String> {
23822382

23832383
@Override
23842384
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
2385-
return new String(Files.readAllBytes(fileToPath(f)), Charset.defaultCharset());
2385+
return Files.readString(fileToPath(f), Charset.defaultCharset());
23862386
}
23872387
}
23882388

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

+6-14
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@
100100
import java.io.PrintWriter;
101101
import java.io.Serializable;
102102
import java.io.StringWriter;
103-
import java.io.UnsupportedEncodingException;
104103
import java.lang.management.LockInfo;
105104
import java.lang.management.ManagementFactory;
106105
import java.lang.management.MonitorInfo;
@@ -747,10 +746,7 @@ public static String appendSpaceIfNotNull(String n) {
747746
public static String nbspIndent(String size) {
748747
int i = size.indexOf('x');
749748
i = Integer.parseInt(i > 0 ? size.substring(0, i) : size) / 10;
750-
StringBuilder buf = new StringBuilder(30);
751-
for (int j = 2; j <= i; j++)
752-
buf.append("&nbsp;");
753-
return buf.toString();
749+
return "&nbsp;".repeat(Math.max(0, i - 1));
754750
}
755751

756752
public static String getWin32ErrorMessage(IOException e) {
@@ -777,11 +773,7 @@ public static String urlEncode(String s) {
777773
if (s == null) {
778774
return "";
779775
}
780-
try {
781-
return URLEncoder.encode(s, StandardCharsets.UTF_8.name());
782-
} catch (UnsupportedEncodingException e) {
783-
throw new Error(e); // impossible
784-
}
776+
return URLEncoder.encode(s, StandardCharsets.UTF_8);
785777
}
786778

787779
public static String escape(String s) {
@@ -1933,19 +1925,19 @@ public void calcCheckUrl(Map attributes, String userDefined, Object descriptor,
19331925
*
19341926
* Used in {@code task.jelly} to decide if the page should be highlighted.
19351927
*/
1936-
public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException {
1928+
public boolean hyperlinkMatchesCurrentPage(String href) {
19371929
String url = Stapler.getCurrentRequest().getRequestURL().toString();
19381930
if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/");
1939-
url = URLDecoder.decode(url, "UTF-8");
1940-
href = URLDecoder.decode(href, "UTF-8");
1931+
url = URLDecoder.decode(url, StandardCharsets.UTF_8);
1932+
href = URLDecoder.decode(href, StandardCharsets.UTF_8);
19411933
if (url.endsWith("/")) url = url.substring(0, url.length() - 1);
19421934
if (href.endsWith("/")) href = href.substring(0, href.length() - 1);
19431935

19441936
return url.endsWith(href);
19451937
}
19461938

19471939
public <T> List<T> singletonList(T t) {
1948-
return Collections.singletonList(t);
1940+
return List.of(t);
19491941
}
19501942

19511943
/**

core/src/main/java/hudson/PluginManager.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -930,7 +930,7 @@ public void dynamicLoad(File arc, boolean removeExisting, @CheckForNull List<Plu
930930
if (batch != null) {
931931
batch.add(p);
932932
} else {
933-
start(Collections.singletonList(p));
933+
start(List.of(p));
934934
}
935935

936936
} catch (Exception e) {

core/src/main/java/hudson/PluginWrapper.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ public class PluginWrapper implements Comparable<PluginWrapper>, ModelObject {
174174
private final List<Dependency> optionalDependencies;
175175

176176
public List<String> getDependencyErrors() {
177-
return Collections.unmodifiableList(new ArrayList<>(dependencyErrors.keySet()));
177+
return List.copyOf(dependencyErrors.keySet());
178178
}
179179

180180
@Restricted(NoExternalUse.class) // Jelly use
@@ -222,7 +222,7 @@ public boolean hasDerivedDependencyErrors() {
222222
* The core can depend on a plugin if it is bundled. Sometimes it's the only thing that
223223
* depends on the plugin e.g. UI support library bundle plugin.
224224
*/
225-
private static Set<String> CORE_ONLY_DEPENDANT = Collections.singleton("jenkins-core");
225+
private static Set<String> CORE_ONLY_DEPENDANT = Set.of("jenkins-core");
226226

227227
/**
228228
* Set the list of components that depend on this plugin.

core/src/main/java/hudson/StructuredForm.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public static List<JSONObject> toList(JSONObject parent, String propertyName) {
6767
if (v == null)
6868
return Collections.emptyList();
6969
if (v instanceof JSONObject)
70-
return Collections.singletonList((JSONObject) v);
70+
return List.of((JSONObject) v);
7171
if (v instanceof JSONArray)
7272
return (List) v;
7373

core/src/main/java/hudson/WebAppMain.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ public void contextInitialized(ServletContextEvent event) {
140140
// Nicer console log formatting when using mvn jetty:run.
141141
if (Main.isDevelopmentMode && System.getProperty("java.util.logging.config.file") == null) {
142142
try {
143-
Formatter formatter = (Formatter) Class.forName("io.jenkins.lib.support_log_formatter.SupportLogFormatter").newInstance();
143+
Formatter formatter = (Formatter) Class.forName("io.jenkins.lib.support_log_formatter.SupportLogFormatter").getDeclaredConstructor().newInstance();
144144
for (Handler h : Logger.getLogger("").getHandlers()) {
145145
if (h instanceof ConsoleHandler) {
146146
((ConsoleHandler) h).setFormatter(formatter);

core/src/main/java/hudson/cli/CLIAction.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -277,8 +277,8 @@ void run() throws IOException, InterruptedException {
277277
wait();
278278
}
279279
}
280-
PrintStream stdout = new PrintStream(streamStdout(), false, encoding.name());
281-
PrintStream stderr = new PrintStream(streamStderr(), true, encoding.name());
280+
PrintStream stdout = new PrintStream(streamStdout(), false, encoding);
281+
PrintStream stderr = new PrintStream(streamStderr(), true, encoding);
282282
if (args.isEmpty()) {
283283
stderr.println("Connection closed before arguments received");
284284
sendExit(2);

core/src/main/java/hudson/cli/CLICommand.java

+4-22
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
import java.io.InputStream;
4343
import java.io.PrintStream;
4444
import java.io.UncheckedIOException;
45-
import java.io.UnsupportedEncodingException;
4645
import java.lang.reflect.InvocationTargetException;
4746
import java.lang.reflect.Type;
4847
import java.nio.charset.Charset;
@@ -415,11 +414,7 @@ public final String getSingleLineSummary() {
415414
} catch (InterruptedException e) {
416415
throw new RuntimeException(e);
417416
}
418-
try {
419-
return out.toString(charset.name());
420-
} catch (UnsupportedEncodingException e) {
421-
throw new AssertionError(e);
422-
}
417+
return out.toString(charset);
423418
}
424419

425420
/**
@@ -437,11 +432,7 @@ public final String getUsage() {
437432
} catch (InterruptedException e) {
438433
throw new RuntimeException(e);
439434
}
440-
try {
441-
return out.toString(charset.name());
442-
} catch (UnsupportedEncodingException e) {
443-
throw new AssertionError(e);
444-
}
435+
return out.toString(charset);
445436
}
446437

447438
/**
@@ -458,20 +449,11 @@ public final String getLongDescription() {
458449
} catch (InterruptedException e) {
459450
throw new RuntimeException(e);
460451
}
461-
PrintStream ps;
462-
try {
463-
ps = new PrintStream(out, false, charset.name());
464-
} catch (UnsupportedEncodingException e) {
465-
throw new AssertionError(e);
466-
}
452+
PrintStream ps = new PrintStream(out, false, charset);
467453

468454
printUsageSummary(ps);
469455
ps.close();
470-
try {
471-
return out.toString(charset.name());
472-
} catch (UnsupportedEncodingException e) {
473-
throw new AssertionError(e);
474-
}
456+
return out.toString(charset);
475457
}
476458

477459
/**

core/src/main/java/hudson/model/AbstractBuild.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -925,7 +925,7 @@ public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOEx
925925
@Override
926926
@NonNull public List<ChangeLogSet<? extends ChangeLogSet.Entry>> getChangeSets() {
927927
ChangeLogSet<? extends ChangeLogSet.Entry> cs = getChangeSet();
928-
return cs.isEmptySet() ? Collections.emptyList() : Collections.singletonList(cs);
928+
return cs.isEmptySet() ? Collections.emptyList() : List.of(cs);
929929
}
930930

931931
/**
@@ -995,7 +995,7 @@ public EnvironmentList getEnvironments() {
995995
return new EnvironmentList(buildEnvironments);
996996
}
997997

998-
return new EnvironmentList(buildEnvironments == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(buildEnvironments)));
998+
return new EnvironmentList(buildEnvironments == null ? Collections.emptyList() : List.copyOf(buildEnvironments));
999999
}
10001000

10011001
public Calendar due() {

core/src/main/java/hudson/model/Actionable.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import java.util.Collection;
3232
import java.util.Collections;
3333
import java.util.List;
34+
import java.util.Set;
3435
import java.util.concurrent.CopyOnWriteArrayList;
3536
import java.util.logging.Level;
3637
import java.util.logging.Logger;
@@ -227,7 +228,7 @@ public boolean removeAction(@Nullable Action a) {
227228
return false;
228229
}
229230
// CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
230-
return getActions().removeAll(Collections.singleton(a));
231+
return getActions().removeAll(Set.of(a));
231232
}
232233

233234
/**

core/src/main/java/hudson/model/Descriptor.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -59,13 +59,13 @@
5959
import java.util.ArrayList;
6060
import java.util.Arrays;
6161
import java.util.Collection;
62-
import java.util.Collections;
6362
import java.util.HashMap;
6463
import java.util.IdentityHashMap;
6564
import java.util.LinkedHashMap;
6665
import java.util.List;
6766
import java.util.Locale;
6867
import java.util.Map;
68+
import java.util.Set;
6969
import java.util.concurrent.ConcurrentHashMap;
7070
import java.util.logging.Level;
7171
import java.util.logging.Logger;
@@ -863,7 +863,7 @@ Permission getRequiredGlobalConfigPagePermission() {
863863
}
864864

865865
private String getViewPage(Class<?> clazz, String pageName, String defaultValue) {
866-
return getViewPage(clazz, Collections.singleton(pageName), defaultValue);
866+
return getViewPage(clazz, Set.of(pageName), defaultValue);
867867
}
868868

869869
private String getViewPage(Class<?> clazz, Collection<String> pageNames, String defaultValue) {
@@ -978,7 +978,7 @@ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException,
978978
rsp.setContentType("text/html;charset=UTF-8");
979979
try (InputStream in = url.openStream()) {
980980
String literal = IOUtils.toString(in, StandardCharsets.UTF_8);
981-
rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL", req.getContextPath())));
981+
rsp.getWriter().println(Util.replaceMacro(literal, Map.of("rootURL", req.getContextPath())));
982982
}
983983
return;
984984
}

core/src/main/java/hudson/model/DirectoryBrowserSupport.java

+2-6
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939
import java.util.Arrays;
4040
import java.util.Calendar;
4141
import java.util.Collection;
42-
import java.util.Collections;
4342
import java.util.Comparator;
4443
import java.util.GregorianCalendar;
4544
import java.util.LinkedHashMap;
@@ -507,10 +506,7 @@ private List<Path> buildParentPath(String pathList, int restSize) {
507506

508507
private static String createBackRef(int times) {
509508
if (times == 0) return "./";
510-
StringBuilder buf = new StringBuilder(3 * times);
511-
for (int i = 0; i < times; i++)
512-
buf.append("../");
513-
return buf.toString();
509+
return "../".repeat(times);
514510
}
515511

516512
private static void zip(StaplerResponse rsp, VirtualFile root, VirtualFile dir, String glob) throws IOException, InterruptedException {
@@ -764,7 +760,7 @@ private static List<List<Path>> buildChildPaths(VirtualFile cur, Locale locale)
764760
for (VirtualFile f : files) {
765761
Path p = new Path(Util.rawEncode(f.getName()), f.getName(), f.isDirectory(), f.length(), f.canRead(), f.lastModified());
766762
if (!f.isDirectory()) {
767-
r.add(Collections.singletonList(p));
763+
r.add(List.of(p));
768764
} else {
769765
// find all empty intermediate directory
770766
List<Path> l = new ArrayList<>();

core/src/main/java/hudson/model/DownloadService.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ public FormValidation updateNow() throws IOException {
388388
}
389389
String jsonString;
390390
try {
391-
jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8")));
391+
jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8)));
392392
toolInstallerMetadataExists = true;
393393
} catch (Exception e) {
394394
LOGGER.log(Level.FINE, "Could not load json from " + site, e);

0 commit comments

Comments
 (0)