Skip to content

Commit

Permalink
Use Java 17 features in source code (#1186)
Browse files Browse the repository at this point in the history
https://docs.openrewrite.org/running-recipes/popular-recipe-guides/migrate-to-java-17
provided the transformations and they all pass automated tests.

Several nice readability improvements are provided by Java 17.
  • Loading branch information
MarkEWaite authored Sep 13, 2024
1 parent c1c888d commit 0f8f753
Show file tree
Hide file tree
Showing 26 changed files with 193 additions and 173 deletions.
2 changes: 1 addition & 1 deletion src/main/java/hudson/plugins/git/Branch.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ private static String strip(String name) {
*/
@Override
public String toString() {
return String.format("Branch %s(%s)", name, getSHA1String());
return "Branch %s(%s)".formatted(name, getSHA1String());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/hudson/plugins/git/IndexEntry.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public void setFile(String file) {
*/
@Override
public String toString() {
return String.format("IndexEntry[mode=%s,type=%s,file=%s,object=%s]", mode, type, file, object);
return "IndexEntry[mode=%s,type=%s,file=%s,object=%s]".formatted(mode, type, file, object);
}

/**
Expand Down
34 changes: 17 additions & 17 deletions src/main/java/org/jenkinsci/plugins/gitclient/CliGitAPIImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclEntryPermission;
import java.nio.file.attribute.AclEntryType;
Expand Down Expand Up @@ -1976,7 +1975,7 @@ Path createTempFile(String prefix, String suffix) throws IOException {
return createTempFileInSystemDir(prefix, suffix);
}
}
Path tmpPath = Paths.get(workspaceTmp.getAbsolutePath());
Path tmpPath = Path.of(workspaceTmp.getAbsolutePath());
if (workspaceTmp.getAbsolutePath().contains("%")) {
// Avoid ssh token expansion on all platforms
return createTempFileInSystemDir(prefix, suffix);
Expand Down Expand Up @@ -2098,8 +2097,7 @@ private String launchCommandWithCredentials(
}
}
try {
if (credentials instanceof SSHUserPrivateKey) {
SSHUserPrivateKey sshUser = (SSHUserPrivateKey) credentials;
if (credentials instanceof SSHUserPrivateKey sshUser) {

Check warning on line 2100 in src/main/java/org/jenkinsci/plugins/gitclient/CliGitAPIImpl.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 2100 is only partially covered, one branch is missing
listener.getLogger().println("using GIT_SSH to set credentials " + sshUser.getDescription());

key = createSshKeyFile(sshUser);
Expand Down Expand Up @@ -2130,8 +2128,7 @@ private String launchCommandWithCredentials(
env.put("DISPLAY", ":");
}

} else if (credentials instanceof StandardUsernamePasswordCredentials) {
StandardUsernamePasswordCredentials userPass = (StandardUsernamePasswordCredentials) credentials;
} else if (credentials instanceof StandardUsernamePasswordCredentials userPass) {
listener.getLogger().println("using GIT_ASKPASS to set credentials " + userPass.getDescription());

usernameFile = createUsernameFile(userPass);
Expand Down Expand Up @@ -2207,7 +2204,7 @@ private Boolean fixSELinuxLabel(Path key, String label) {
// "untrusted" key files.
// Check that tools exist and then if SELinux subsystem is activated
// Otherwise calling the tools just pollutes build log with errors
if (Files.isExecutable(Paths.get("/usr/bin/chcon"))) {
if (Files.isExecutable(Path.of("/usr/bin/chcon"))) {
// SELinux may actually forbid us to read system paths, so
// there are a couple of ways to try checking if it is enabled
// (whether this run needs to worry about security labels) and
Expand All @@ -2222,10 +2219,10 @@ private Boolean fixSELinuxLabel(Path key, String label) {
try {
// A process should always have rights to inspect itself, but
// on some systems even this read returns "Invalid argument"
if (Files.isRegularFile(Paths.get("/proc/self/attr/current"))) {
if (Files.isRegularFile(Path.of("/proc/self/attr/current"))) {
String s;
try (BufferedReader br =
Files.newBufferedReader(Paths.get("/proc/self/attr/current"), StandardCharsets.UTF_8)) {
Files.newBufferedReader(Path.of("/proc/self/attr/current"), StandardCharsets.UTF_8)) {
s = br.readLine();
}
if ("unconfined".equals(s)) {
Expand All @@ -2244,16 +2241,16 @@ private Boolean fixSELinuxLabel(Path key, String label) {
}

try {
if (!Files.isDirectory(Paths.get("/sys/fs/selinux"))) {
if (!Files.isDirectory(Path.of("/sys/fs/selinux"))) {
// Assuming that lack of rights to read this is an
// exception caught below, not a false return here?
return true;
}

if (Files.isRegularFile(Paths.get("/sys/fs/selinux/enforce"))) {
if (Files.isRegularFile(Path.of("/sys/fs/selinux/enforce"))) {
String s;
try (BufferedReader br =
Files.newBufferedReader(Paths.get("/sys/fs/selinux/enforce"), StandardCharsets.UTF_8)) {
Files.newBufferedReader(Path.of("/sys/fs/selinux/enforce"), StandardCharsets.UTF_8)) {
s = br.readLine();
}
if ("0".equals(s)) {
Expand Down Expand Up @@ -2292,10 +2289,13 @@ private Boolean fixSELinuxLabel(Path key, String label) {

if (!clue_sysfs && !clue_proc) { // && !clue_ls
listener.getLogger()
.println("[INFO] SELinux is present on the host "
+ "and we could not confirm that it does not apply actively: "
+ "will try to relabel temporary files now; this may complain "
+ "if context labeling not applicable after all");
.println(

Check warning on line 2292 in src/main/java/org/jenkinsci/plugins/gitclient/CliGitAPIImpl.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 2207-2292 are not covered by tests
"""
[INFO] SELinux is present on the host \
and we could not confirm that it does not apply actively: \
will try to relabel temporary files now; this may complain \
if context labeling not applicable after all\
""");
}

ArgumentListBuilder args = new ArgumentListBuilder();
Expand Down Expand Up @@ -2721,7 +2721,7 @@ private Path createUnixGitSSH(Path key, String user, Path knownHosts) throws IOE

private Path createNonBusyExecutable(Path p) throws IOException {
p.toFile().setExecutable(true, true);
Path p_copy = Paths.get(p.toString() + "-copy");
Path p_copy = Path.of(p.toString() + "-copy");

// JENKINS-48258 git client plugin occasionally fails with "text file busy" error
// The following creates a copy of the generated file and deletes the original
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ private List<ToolProperty<?>> instantiateProperties(
return toolProperties;
}
final Configurator<ToolProperty> configurator = context.lookupOrFail(ToolProperty.class);
if (props instanceof Sequence) {
Sequence s = (Sequence) props;
if (props instanceof Sequence s) {

Check warning on line 104 in src/main/java/org/jenkinsci/plugins/gitclient/GitToolConfigurator.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 104 is only partially covered, one branch is missing
for (CNode cNode : s) {
toolProperties.add(configurator.configure(cNode, context));
}
Expand Down
25 changes: 12 additions & 13 deletions src/main/java/org/jenkinsci/plugins/gitclient/JGitAPIImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -236,7 +235,7 @@ public SshdSessionFactory buildSshdSessionFactory(@NonNull final HostKeyVerifier
.setConfigStoreFactory((homeDir, configFile, localUserName) -> {
String configFilePath = SystemProperties.getString(SSH_CONFIG_PATH);
if (configFilePath != null) {
Path path = Paths.get(configFilePath);
Path path = Path.of(configFilePath);

Check warning on line 238 in src/main/java/org/jenkinsci/plugins/gitclient/JGitAPIImpl.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 238 is not covered by tests
homeDir = path.toFile().getParentFile();
configFile = path.toFile();
}
Expand Down Expand Up @@ -955,8 +954,8 @@ public Map<String, ObjectId> getHeadRev(String url) throws GitException, Interru

private TransportConfigCallback getTransportConfigCallback() {
return transport -> {
if (transport instanceof SshTransport) {
((SshTransport) transport).setSshSessionFactory(buildSshdSessionFactory(this.hostKeyVerifierFactory));
if (transport instanceof SshTransport sshTransport) {
sshTransport.setSshSessionFactory(buildSshdSessionFactory(this.hostKeyVerifierFactory));
}
if (transport instanceof HttpTransport) {
((TransportHttp) transport)
Expand All @@ -966,8 +965,8 @@ private TransportConfigCallback getTransportConfigCallback() {
}

private void decorateTransport(Transport tn) {
if (tn instanceof SshTransport) {
((SshTransport) tn).setSshSessionFactory(buildSshdSessionFactory(getHostKeyFactory()));
if (tn instanceof SshTransport transport) {

Check warning on line 968 in src/main/java/org/jenkinsci/plugins/gitclient/JGitAPIImpl.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 968 is only partially covered, one branch is missing
transport.setSshSessionFactory(buildSshdSessionFactory(getHostKeyFactory()));

Check warning on line 969 in src/main/java/org/jenkinsci/plugins/gitclient/JGitAPIImpl.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 969 is not covered by tests
}
if (tn instanceof HttpTransport) {
((TransportHttp) tn).setHttpConnectionFactory(new PreemptiveAuthHttpClientConnectionFactory(getProvider()));
Expand Down Expand Up @@ -2239,7 +2238,7 @@ private String fixRefSpec(@NonNull String srcRefspec, Repository repository) thr
case 0: // for the source ref. we use the repository to determine what should be pushed
Ref ref = repository.findRef(specs[spec]);
if (ref == null) {
throw new IOException(String.format("Ref %s not found.", specs[spec]));
throw new IOException("Ref %s not found.".formatted(specs[spec]));
}
specs[spec] = ref.getTarget().getName();
break;
Expand Down Expand Up @@ -2947,11 +2946,11 @@ public boolean reaches(RevCommit c) {
}

public String describe(ObjectId tip) throws IOException {
return String.format(
"%s-%d-g%s",
tag.getName().substring(R_TAGS.length()),
depth,
or.abbreviate(tip).name());
return "%s-%d-g%s"
.formatted(
tag.getName().substring(R_TAGS.length()),
depth,
or.abbreviate(tip).name());
}
}
List<Candidate> candidates = new ArrayList<>(); // all the candidates we find
Expand Down Expand Up @@ -3049,7 +3048,7 @@ public List<IndexEntry> lsTree(String treeIsh, boolean recursive) throws GitExce
while (tree.next()) {
RevObject rev = w.parseAny(tree.getObjectId(0));
r.add(new IndexEntry(
String.format("%06o", tree.getRawMode(0)),
"%06o".formatted(tree.getRawMode(0)),
typeString(rev.getType()),
tree.getObjectId(0).name(),
tree.getNameString()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ static class Invocation implements Serializable {
parameterTypes[i] = paramTypes[i].getName();
}
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof OutputStream) {
args[i] = new RemoteOutputStream((OutputStream) args[i]);
if (args[i] instanceof OutputStream stream) {
args[i] = new RemoteOutputStream(stream);
}
if (args[i] instanceof Writer) {
args[i] = new RemoteWriter((Writer) args[i]);
if (args[i] instanceof Writer writer) {
args[i] = new RemoteWriter(writer);

Check warning on line 86 in src/main/java/org/jenkinsci/plugins/gitclient/RemoteGitImpl.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 82-86 are not covered by tests
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,18 +85,17 @@ public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCreden
StandardUsernamePasswordCredentials _cred = (StandardUsernamePasswordCredentials) cred;

for (CredentialItem i : items) {
if (i instanceof CredentialItem.Username) {
((CredentialItem.Username) i).setValue(_cred.getUsername());
if (i instanceof CredentialItem.Username username) {
username.setValue(_cred.getUsername());
continue;
}
if (i instanceof CredentialItem.Password) {
((CredentialItem.Password) i)
.setValue(_cred.getPassword().getPlainText().toCharArray());
if (i instanceof CredentialItem.Password password) {
password.setValue(_cred.getPassword().getPlainText().toCharArray());
continue;
}
if (i instanceof CredentialItem.StringType) {
if (i instanceof CredentialItem.StringType type) {
if (i.getPromptText().equals("Password: ")) {
((CredentialItem.StringType) i).setValue(_cred.getPassword().getPlainText());
type.setValue(_cred.getPassword().getPlainText());
continue;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,7 @@ static NTCredentials createNTCredentials(final String userName, final String pas
private static void configureProxy(final HttpClientBuilder builder, final Proxy proxy) {
if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
final SocketAddress socketAddress = proxy.address();
if (socketAddress instanceof InetSocketAddress) {
final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
if (socketAddress instanceof InetSocketAddress inetSocketAddress) {

Check warning on line 264 in src/main/java/org/jenkinsci/plugins/gitclient/jgit/PreemptiveAuthHttpClientConnection.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 264 is not covered by tests
final String proxyHost = inetSocketAddress.getHostName();
final int proxyPort = inetSocketAddress.getPort();
final HttpHost httpHost = new HttpHost(proxyHost, proxyPort);
Expand Down Expand Up @@ -310,8 +309,7 @@ public String getResponseMessage() throws IOException {
private void execute() throws IOException {
if (resp == null) {
if (entity != null) {
if (req instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
if (req instanceof HttpEntityEnclosingRequest eReq) {

Check warning on line 312 in src/main/java/org/jenkinsci/plugins/gitclient/jgit/PreemptiveAuthHttpClientConnection.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 312 is only partially covered, one branch is missing
eReq.setEntity(entity);
}
resp = getClient().execute(req);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,26 +156,23 @@ public boolean get(URIish uri, CredentialItem... credentialItems) throws Unsuppo
return false;
}
for (CredentialItem i : credentialItems) {
if (i instanceof StandardUsernameCredentialsCredentialItem && c instanceof StandardUsernameCredentials) {
((StandardUsernameCredentialsCredentialItem) i).setValue((StandardUsernameCredentials) c);
if (i instanceof StandardUsernameCredentialsCredentialItem item

Check warning on line 159 in src/main/java/org/jenkinsci/plugins/gitclient/jgit/SmartCredentialsProvider.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 159 is only partially covered, one branch is missing
&& c instanceof StandardUsernameCredentials credentials) {
item.setValue(credentials);
continue;
}
if (i instanceof CredentialItem.Username && c instanceof UsernameCredentials) {
((CredentialItem.Username) i).setValue(((UsernameCredentials) c).getUsername());
if (i instanceof CredentialItem.Username username && c instanceof UsernameCredentials credentials) {

Check warning on line 164 in src/main/java/org/jenkinsci/plugins/gitclient/jgit/SmartCredentialsProvider.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 164 is only partially covered, one branch is missing
username.setValue(credentials.getUsername());
continue;
}
if (i instanceof CredentialItem.Password && c instanceof PasswordCredentials) {
((CredentialItem.Password) i)
.setValue(((PasswordCredentials) c)
.getPassword()
.getPlainText()
.toCharArray());
if (i instanceof CredentialItem.Password password && c instanceof PasswordCredentials credentials) {

Check warning on line 168 in src/main/java/org/jenkinsci/plugins/gitclient/jgit/SmartCredentialsProvider.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 168 is only partially covered, one branch is missing
password.setValue(credentials.getPassword().getPlainText().toCharArray());
continue;
}
if (i instanceof CredentialItem.StringType) {
if (i.getPromptText().equals("Password: ") && c instanceof PasswordCredentials) {
if (i.getPromptText().equals("Password: ") && c instanceof PasswordCredentials credentials) {

Check warning on line 173 in src/main/java/org/jenkinsci/plugins/gitclient/jgit/SmartCredentialsProvider.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 173 is only partially covered, one branch is missing
((CredentialItem.StringType) i)
.setValue(((PasswordCredentials) c).getPassword().getPlainText());
.setValue(credentials.getPassword().getPlainText());
continue;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,15 @@ public ServerKeyDatabase.Configuration getServerKeyDatabaseConfiguration() {

private void logHint(TaskListener listener) {
listener.getLogger()
.println(HyperlinkNote.encodeTo(
"https://plugins.jenkins.io/git-client/#plugin-content-ssh-host-key-verification",
"You're using 'Known hosts file' strategy to verify ssh host keys,"
+ " but your known_hosts file does not exist, please go to "
+ "'Manage Jenkins' -> 'Security' -> 'Git Host Key Verification Configuration' "
+ "and configure host key verification."));
.println(
HyperlinkNote.encodeTo(
"https://plugins.jenkins.io/git-client/#plugin-content-ssh-host-key-verification",
"""
You're using 'Known hosts file' strategy to verify ssh host keys,\
but your known_hosts file does not exist, please go to \
'Manage Jenkins' -> 'Security' -> 'Git Host Key Verification Configuration' \
and configure host key verification.\
"""));
LOGGER.log(
Level.FINEST,
"Known hosts file {0} not found, but verifying host keys with known hosts file",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ public AbstractCliGitHostKeyVerifier forCliGit(TaskListener listener) {
if (File.pathSeparatorChar
== ';') { // check whether on Windows or not without sending Functions over remoting
// no escaping for windows because created temp file can't contain spaces
userKnownHostsFileFlag = String.format(" -o UserKnownHostsFile=%s", escapePath(tempKnownHosts));
userKnownHostsFileFlag = " -o UserKnownHostsFile=%s".formatted(escapePath(tempKnownHosts));

Check warning on line 37 in src/main/java/org/jenkinsci/plugins/gitclient/verifier/ManuallyProvidedKeyVerifier.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 37 is not covered by tests
} else {
// escaping needed in case job name contains spaces
userKnownHostsFileFlag =
String.format(" -o UserKnownHostsFile=\\\"\"\"%s\\\"\"\"", escapePath(tempKnownHosts));
" -o UserKnownHostsFile=\\\"\"\"%s\\\"\"\"".formatted(escapePath(tempKnownHosts));
}
return "-o StrictHostKeyChecking=yes " + userKnownHostsFileFlag;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import java.io.File;
import java.nio.file.Paths;
import java.nio.file.Path;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;

public abstract class SshHostKeyVerificationStrategy<T extends HostKeyVerifierFactory>
extends AbstractDescribableImpl<SshHostKeyVerificationStrategy<T>> implements ExtensionPoint {

public static final String KNOWN_HOSTS_DEFAULT =
Paths.get(System.getProperty("user.home"), ".ssh", "known_hosts").toString();
Path.of(System.getProperty("user.home"), ".ssh", "known_hosts").toString();
private static final String JGIT_KNOWN_HOSTS_PROPERTY =
SshHostKeyVerificationStrategy.class.getName() + ".jgit_known_hosts_file";
private static final String JGIT_KNOWN_HOSTS_FILE_PATH =
Expand Down
Loading

0 comments on commit 0f8f753

Please sign in to comment.