Skip to content

Commit

Permalink
Use Java 11 methods where possible (#6700)
Browse files Browse the repository at this point in the history
  • Loading branch information
basil authored Jun 30, 2022
1 parent 1a6d9f0 commit 6d17999
Show file tree
Hide file tree
Showing 148 changed files with 419 additions and 527 deletions.
5 changes: 2 additions & 3 deletions cli/src/main/java/hudson/cli/CLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
import java.security.KeyPair;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
Expand Down Expand Up @@ -267,7 +266,7 @@ public boolean verify(String s, SSLSession sslSession) {
}

if (args.isEmpty())
args = Collections.singletonList("help"); // default to help
args = List.of("help"); // default to help

if (mode == null) {
mode = Mode.HTTP;
Expand Down Expand Up @@ -346,7 +345,7 @@ class Authenticator extends ClientEndpointConfig.Configurator {
@Override
public void beforeRequest(Map<String, List<String>> headers) {
if (factory.authorization != null) {
headers.put("Authorization", Collections.singletonList(factory.authorization));
headers.put("Authorization", List.of(factory.authorization));
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions cli/src/main/java/hudson/cli/SSHCLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import java.net.URLConnection;
import java.security.KeyPair;
import java.security.PublicKey;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
Expand Down Expand Up @@ -114,7 +113,7 @@ public boolean verifyServerKey(ClientSession clientSession, SocketAddress remote
WaitableFuture wf = channel.open();
wf.await();

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

if (waitMask.contains(ClientChannelEvent.TIMEOUT)) {
throw new SocketTimeoutException("Failed to retrieve command result in time: " + command);
Expand Down
4 changes: 2 additions & 2 deletions cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,9 @@ void newop() throws IOException {
while (server.stdin.size() == 0) {
Thread.sleep(100);
}
assertEquals("hello", server.stdin.toString(Charset.defaultCharset().name()));
assertEquals("hello", server.stdin.toString(Charset.defaultCharset()));
assertEquals("command", server.arg);
assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset().name()));
assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset()));
assertEquals(2, client.code);
}

Expand Down
7 changes: 4 additions & 3 deletions core/src/main/java/hudson/ClassicPluginStrategy.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
Expand Down Expand Up @@ -338,7 +339,7 @@ public <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson huds
List<ExtensionFinder> finders;
if (type == ExtensionFinder.class) {
// Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders
finders = Collections.singletonList(new ExtensionFinder.Sezpoz());
finders = List.of(new ExtensionFinder.Sezpoz());
} else {
finders = hudson.getExtensionList(ExtensionFinder.class);
}
Expand Down Expand Up @@ -597,7 +598,7 @@ static final class DependencyClassLoader extends ClassLoader {
DependencyClassLoader(ClassLoader parent, File archive, List<Dependency> dependencies, PluginManager pluginManager) {
super(parent);
this._for = archive;
this.dependencies = Collections.unmodifiableList(new ArrayList<>(dependencies));
this.dependencies = List.copyOf(dependencies);
this.pluginManager = pluginManager;
}

Expand Down Expand Up @@ -629,7 +630,7 @@ protected List<PluginWrapper> getEdges(PluginWrapper pw) {
for (Dependency d : dependencies) {
PluginWrapper p = pluginManager.getPlugin(d.shortName);
if (p != null && p.isActive())
cgd.run(Collections.singleton(p));
cgd.run(Set.of(p));
}
} catch (CycleDetectedException e) {
throw new AssertionError(e); // such error should have been reported earlier
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/hudson/ExtensionFinder.java
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ protected void configure() {
}

public List<IndexItem<?, Object>> getLoadedIndex() {
return Collections.unmodifiableList(new ArrayList<>(loadedIndex));
return List.copyOf(loadedIndex);
}

@Override
Expand Down Expand Up @@ -645,7 +645,7 @@ private List<IndexItem<Extension, Object>> getIndices() {
// 5. dead lock
if (indices == null) {
ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader;
indices = Collections.unmodifiableList(StreamSupport.stream(Index.load(Extension.class, Object.class, cl).spliterator(), false).collect(Collectors.toList()));
indices = StreamSupport.stream(Index.load(Extension.class, Object.class, cl).spliterator(), false).collect(Collectors.toUnmodifiableList());
}
return indices;
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/hudson/FilePath.java
Original file line number Diff line number Diff line change
Expand Up @@ -2382,7 +2382,7 @@ private static class ReadToString extends MasterToSlaveFileCallable<String> {

@Override
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return new String(Files.readAllBytes(fileToPath(f)), Charset.defaultCharset());
return Files.readString(fileToPath(f), Charset.defaultCharset());
}
}

Expand Down
20 changes: 6 additions & 14 deletions core/src/main/java/hudson/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
Expand Down Expand Up @@ -747,10 +746,7 @@ public static String appendSpaceIfNotNull(String n) {
public static String nbspIndent(String size) {
int i = size.indexOf('x');
i = Integer.parseInt(i > 0 ? size.substring(0, i) : size) / 10;
StringBuilder buf = new StringBuilder(30);
for (int j = 2; j <= i; j++)
buf.append("&nbsp;");
return buf.toString();
return "&nbsp;".repeat(Math.max(0, i - 1));
}

public static String getWin32ErrorMessage(IOException e) {
Expand All @@ -777,11 +773,7 @@ public static String urlEncode(String s) {
if (s == null) {
return "";
}
try {
return URLEncoder.encode(s, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
return URLEncoder.encode(s, StandardCharsets.UTF_8);
}

public static String escape(String s) {
Expand Down Expand Up @@ -1933,19 +1925,19 @@ public void calcCheckUrl(Map attributes, String userDefined, Object descriptor,
*
* Used in {@code task.jelly} to decide if the page should be highlighted.
*/
public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException {
public boolean hyperlinkMatchesCurrentPage(String href) {
String url = Stapler.getCurrentRequest().getRequestURL().toString();
if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/");
url = URLDecoder.decode(url, "UTF-8");
href = URLDecoder.decode(href, "UTF-8");
url = URLDecoder.decode(url, StandardCharsets.UTF_8);
href = URLDecoder.decode(href, StandardCharsets.UTF_8);
if (url.endsWith("/")) url = url.substring(0, url.length() - 1);
if (href.endsWith("/")) href = href.substring(0, href.length() - 1);

return url.endsWith(href);
}

public <T> List<T> singletonList(T t) {
return Collections.singletonList(t);
return List.of(t);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/hudson/PluginManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,7 @@ public void dynamicLoad(File arc, boolean removeExisting, @CheckForNull List<Plu
if (batch != null) {
batch.add(p);
} else {
start(Collections.singletonList(p));
start(List.of(p));
}

} catch (Exception e) {
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/hudson/PluginWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public class PluginWrapper implements Comparable<PluginWrapper>, ModelObject {
private final List<Dependency> optionalDependencies;

public List<String> getDependencyErrors() {
return Collections.unmodifiableList(new ArrayList<>(dependencyErrors.keySet()));
return List.copyOf(dependencyErrors.keySet());
}

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

/**
* Set the list of components that depend on this plugin.
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/hudson/StructuredForm.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public static List<JSONObject> toList(JSONObject parent, String propertyName) {
if (v == null)
return Collections.emptyList();
if (v instanceof JSONObject)
return Collections.singletonList((JSONObject) v);
return List.of((JSONObject) v);
if (v instanceof JSONArray)
return (List) v;

Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/hudson/WebAppMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public void contextInitialized(ServletContextEvent event) {
// Nicer console log formatting when using mvn jetty:run.
if (Main.isDevelopmentMode && System.getProperty("java.util.logging.config.file") == null) {
try {
Formatter formatter = (Formatter) Class.forName("io.jenkins.lib.support_log_formatter.SupportLogFormatter").newInstance();
Formatter formatter = (Formatter) Class.forName("io.jenkins.lib.support_log_formatter.SupportLogFormatter").getDeclaredConstructor().newInstance();
for (Handler h : Logger.getLogger("").getHandlers()) {
if (h instanceof ConsoleHandler) {
((ConsoleHandler) h).setFormatter(formatter);
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/hudson/cli/CLIAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,8 @@ void run() throws IOException, InterruptedException {
wait();
}
}
PrintStream stdout = new PrintStream(streamStdout(), false, encoding.name());
PrintStream stderr = new PrintStream(streamStderr(), true, encoding.name());
PrintStream stdout = new PrintStream(streamStdout(), false, encoding);
PrintStream stderr = new PrintStream(streamStderr(), true, encoding);
if (args.isEmpty()) {
stderr.println("Connection closed before arguments received");
sendExit(2);
Expand Down
26 changes: 4 additions & 22 deletions core/src/main/java/hudson/cli/CLICommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
Expand Down Expand Up @@ -415,11 +414,7 @@ public final String getSingleLineSummary() {
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
return out.toString(charset.name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
return out.toString(charset);
}

/**
Expand All @@ -437,11 +432,7 @@ public final String getUsage() {
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
return out.toString(charset.name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
return out.toString(charset);
}

/**
Expand All @@ -458,20 +449,11 @@ public final String getLongDescription() {
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
PrintStream ps;
try {
ps = new PrintStream(out, false, charset.name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
PrintStream ps = new PrintStream(out, false, charset);

printUsageSummary(ps);
ps.close();
try {
return out.toString(charset.name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
return out.toString(charset);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/hudson/model/AbstractBuild.java
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,7 @@ public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOEx
@Override
@NonNull public List<ChangeLogSet<? extends ChangeLogSet.Entry>> getChangeSets() {
ChangeLogSet<? extends ChangeLogSet.Entry> cs = getChangeSet();
return cs.isEmptySet() ? Collections.emptyList() : Collections.singletonList(cs);
return cs.isEmptySet() ? Collections.emptyList() : List.of(cs);
}

/**
Expand Down Expand Up @@ -995,7 +995,7 @@ public EnvironmentList getEnvironments() {
return new EnvironmentList(buildEnvironments);
}

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

public Calendar due() {
Expand Down
3 changes: 2 additions & 1 deletion core/src/main/java/hudson/model/Actionable.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand Down Expand Up @@ -227,7 +228,7 @@ public boolean removeAction(@Nullable Action a) {
return false;
}
// CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
return getActions().removeAll(Collections.singleton(a));
return getActions().removeAll(Set.of(a));
}

/**
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/java/hudson/model/Descriptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand Down Expand Up @@ -863,7 +863,7 @@ Permission getRequiredGlobalConfigPagePermission() {
}

private String getViewPage(Class<?> clazz, String pageName, String defaultValue) {
return getViewPage(clazz, Collections.singleton(pageName), defaultValue);
return getViewPage(clazz, Set.of(pageName), defaultValue);
}

private String getViewPage(Class<?> clazz, Collection<String> pageNames, String defaultValue) {
Expand Down Expand Up @@ -978,7 +978,7 @@ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException,
rsp.setContentType("text/html;charset=UTF-8");
try (InputStream in = url.openStream()) {
String literal = IOUtils.toString(in, StandardCharsets.UTF_8);
rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL", req.getContextPath())));
rsp.getWriter().println(Util.replaceMacro(literal, Map.of("rootURL", req.getContextPath())));
}
return;
}
Expand Down
8 changes: 2 additions & 6 deletions core/src/main/java/hudson/model/DirectoryBrowserSupport.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
Expand Down Expand Up @@ -507,10 +506,7 @@ private List<Path> buildParentPath(String pathList, int restSize) {

private static String createBackRef(int times) {
if (times == 0) return "./";
StringBuilder buf = new StringBuilder(3 * times);
for (int i = 0; i < times; i++)
buf.append("../");
return buf.toString();
return "../".repeat(times);
}

private static void zip(StaplerResponse rsp, VirtualFile root, VirtualFile dir, String glob) throws IOException, InterruptedException {
Expand Down Expand Up @@ -764,7 +760,7 @@ private static List<List<Path>> buildChildPaths(VirtualFile cur, Locale locale)
for (VirtualFile f : files) {
Path p = new Path(Util.rawEncode(f.getName()), f.getName(), f.isDirectory(), f.length(), f.canRead(), f.lastModified());
if (!f.isDirectory()) {
r.add(Collections.singletonList(p));
r.add(List.of(p));
} else {
// find all empty intermediate directory
List<Path> l = new ArrayList<>();
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/hudson/model/DownloadService.java
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ public FormValidation updateNow() throws IOException {
}
String jsonString;
try {
jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8")));
jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8)));
toolInstallerMetadataExists = true;
} catch (Exception e) {
LOGGER.log(Level.FINE, "Could not load json from " + site, e);
Expand Down
Loading

0 comments on commit 6d17999

Please sign in to comment.