Skip to content

Commit

Permalink
Use Java 17 language features (#1749)
Browse files Browse the repository at this point in the history
* Use Java 17 pattern matching instanceof

Makes the code easier to read by avoding the cast that often follows
an instanceof.

* Use Java 17 @serial annotation

Annotation that may allow future checks for serialization.  No real
benefit today as far as I can tell.

* Use Java 17 string formatting

Slight simplification of the code through OpenRewrite
  • Loading branch information
MarkEWaite authored Mar 2, 2025
1 parent 2780aaf commit 5018cec
Show file tree
Hide file tree
Showing 20 changed files with 64 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -610,12 +610,11 @@ protected Object readResolve() throws ObjectStreamException {

public static GitLabPushTrigger getFromJob(Job<?, ?> job) {
GitLabPushTrigger trigger = null;
if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
ParameterizedJobMixIn.ParameterizedJob<?, ?> p = (ParameterizedJobMixIn.ParameterizedJob) job;
if (job instanceof ParameterizedJobMixIn.ParameterizedJob<?, ?> p) {

Check warning on line 613 in src/main/java/com/dabsquared/gitlabjenkins/GitLabPushTrigger.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 613 is only partially covered, one branch is missing
Collection<Trigger<?>> triggerList = p.getTriggers().values();
for (Trigger<?> t : triggerList) {
if (t instanceof GitLabPushTrigger) {
trigger = (GitLabPushTrigger) t;
if (t instanceof GitLabPushTrigger pushTrigger) {

Check warning on line 616 in src/main/java/com/dabsquared/gitlabjenkins/GitLabPushTrigger.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 616 is only partially covered, one branch is missing
trigger = pushTrigger;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsMatcher;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.Serial;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;

public class GitLabCredentialMatcher implements CredentialsMatcher {

@Serial
private static final long serialVersionUID = -6684402077086938070L;

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public class GitLabEnvironmentContributor extends EnvironmentContributor {
public void buildEnvironmentFor(@NonNull Run r, @NonNull EnvVars envs, @NonNull TaskListener listener)
throws IOException, InterruptedException {
GitLabWebHookCause cause = null;
if (r instanceof MatrixRun) {
MatrixBuild parent = ((MatrixRun) r).getParentBuild();
if (r instanceof MatrixRun run) {
MatrixBuild parent = run.getParentBuild();
if (parent != null) {
cause = (GitLabWebHookCause) parent.getCause(GitLabWebHookCause.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ private String getApiToken(GitlabCredentialResolver credentialResolver) {
}

if (credentials != null) {
if (credentials instanceof GitLabApiToken) {
return ((GitLabApiToken) credentials).getApiToken().getPlainText();
if (credentials instanceof GitLabApiToken token) {

Check warning on line 207 in src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilder.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 207 is only partially covered, one branch is missing
return token.getApiToken().getPlainText();

Check warning on line 208 in src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilder.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 208 is not covered by tests
}
if (credentials instanceof StringCredentials) {
return ((StringCredentials) credentials).getSecret().getPlainText();
if (credentials instanceof StringCredentials stringCredentials) {

Check warning on line 210 in src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilder.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 210 is only partially covered, one branch is missing
return stringCredentials.getSecret().getPlainText();
}
}
throw new IllegalStateException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ protected void perform(Run<?, ?> build, TaskListener listener, GitLabClient clie
mergeRequest.getProjectId(), e.getMessage());
LOGGER.log(
Level.SEVERE,
String.format("Failed to accept merge request for project '%s'", mergeRequest.getProjectId()),
"Failed to accept merge request for project '%s'".formatted(mergeRequest.getProjectId()),
e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,7 @@ protected void perform(Run<?, ?> build, TaskListener listener, GitLabClient clie
mergeRequest.getProjectId(), e.getMessage());
LOGGER.log(
Level.SEVERE,
String.format(
"Failed to add comment on Merge Request for project '%s'", mergeRequest.getProjectId()),
"Failed to add comment on Merge Request for project '%s'".formatted(mergeRequest.getProjectId()),

Check warning on line 190 in src/main/java/com/dabsquared/gitlabjenkins/publisher/GitLabMessagePublisher.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 190 is not covered by tests
e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ protected void perform(Run<?, ?> build, TaskListener listener, GitLabClient clie
mergeRequest.getProjectId(), e.getMessage());
LOGGER.log(
Level.SEVERE,
String.format(
"Failed to remove vote on Merge Request for project '%s'", mergeRequest.getProjectId()),
"Failed to remove vote on Merge Request for project '%s'".formatted(mergeRequest.getProjectId()),
e);
}

Expand All @@ -91,7 +90,7 @@ protected void perform(Run<?, ?> build, TaskListener listener, GitLabClient clie
mergeRequest.getProjectId(), e.getMessage());
LOGGER.log(
Level.SEVERE,
String.format("Failed to add vote on Merge Request for project '%s'", mergeRequest.getProjectId()),
"Failed to add vote on Merge Request for project '%s'".formatted(mergeRequest.getProjectId()),

Check warning on line 93 in src/main/java/com/dabsquared/gitlabjenkins/publisher/GitLabVotePublisher.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 93 is not covered by tests
e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,8 @@ private URIish getFirstRepoURL(List<RemoteConfig> repositories) {
private GitSCM getGitSCM(SCMTriggerItem item) {
if (item != null) {
for (SCM scm : item.getSCMs()) {
if (scm instanceof GitSCM) {
return (GitSCM) scm;
if (scm instanceof GitSCM gitSCM) {
return gitSCM;

Check warning on line 162 in src/main/java/com/dabsquared/gitlabjenkins/trigger/branch/ProjectBranchesProvider.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 161-162 are not covered by tests
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,7 @@ protected URIish retrieveUrIish(WebHook hook) {

protected void scheduleBuild(Job<?, ?> job, Action[] actions) {
int projectBuildDelay = 0;
if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
ParameterizedJobMixIn.ParameterizedJob abstractProject = (ParameterizedJobMixIn.ParameterizedJob) job;
if (job instanceof ParameterizedJobMixIn.ParameterizedJob abstractProject) {

Check warning on line 149 in src/main/java/com/dabsquared/gitlabjenkins/trigger/handler/AbstractWebHookTriggerHandler.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 149 is only partially covered, one branch is missing
if (abstractProject.getQuietPeriod() > projectBuildDelay) {
projectBuildDelay = abstractProject.getQuietPeriod();
}
Expand All @@ -168,8 +167,8 @@ protected Job asJob() {
private GitSCM getGitSCM(SCMTriggerItem item) {
if (item != null) {
for (SCM scm : item.getSCMs()) {
if (scm instanceof GitSCM) {
return (GitSCM) scm;
if (scm instanceof GitSCM gitSCM) {

Check warning on line 170 in src/main/java/com/dabsquared/gitlabjenkins/trigger/handler/AbstractWebHookTriggerHandler.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 170 is only partially covered, one branch is missing
return gitSCM;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ public void cancelPendingBuilds(Job<?, ?> job, Integer projectId, String branch)

private GitLabWebHookCause getGitLabWebHookCauseData(Queue.Item item) {
for (Cause cause : item.getCauses()) {
if (cause instanceof GitLabWebHookCause) {
return (GitLabWebHookCause) cause;
if (cause instanceof GitLabWebHookCause hookCause) {

Check warning on line 50 in src/main/java/com/dabsquared/gitlabjenkins/trigger/handler/PendingBuildsHandler.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 50 is only partially covered, one branch is missing
return hookCause;
}
}
return null;
Expand Down Expand Up @@ -87,9 +87,9 @@ private void setCommitStatusCancelledIfNecessary(CauseData causeData, Job<?, ?>
}

public static String resolvePendingBuildName(Job<?, ?> job) {
if (job instanceof AbstractProject) {
GitLabCommitStatusPublisher publisher = (GitLabCommitStatusPublisher)
((AbstractProject) job).getPublishersList().get(GitLabCommitStatusPublisher.class);
if (job instanceof AbstractProject project) {
GitLabCommitStatusPublisher publisher =
(GitLabCommitStatusPublisher) project.getPublishersList().get(GitLabCommitStatusPublisher.class);
if (publisher != null) {
return publisher.getName();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,11 @@ public void handle(
BranchFilter branchFilter,
MergeRequestLabelFilter mergeRequestLabelFilter) {
try {
if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
ParameterizedJob<?, ?> project = (ParameterizedJobMixIn.ParameterizedJob) job;
if (job instanceof ParameterizedJob<?, ?> project) {
GitLabConnectionProperty property = job.getProperty(GitLabConnectionProperty.class);
Collection<Trigger<?>> triggerList = project.getTriggers().values();
for (Trigger<?> t : triggerList) {
if (t instanceof GitLabPushTrigger) {
final GitLabPushTrigger trigger = (GitLabPushTrigger) t;
if (t instanceof GitLabPushTrigger trigger) {
Integer projectId = hook.getProjectId();
if (property != null && property.getClient() != null && projectId != null && trigger != null) {
GitLabClient client = property.getClient();
Expand Down Expand Up @@ -206,8 +204,7 @@ private void setCommitStatusPendingIfNecessary(Job<?, ?> job, Integer projectId,

private void scheduleBuild(Job<?, ?> job, Action[] actions) {
int projectBuildDelay = 0;
if (job instanceof ParameterizedJobMixIn.ParameterizedJob) {
ParameterizedJobMixIn.ParameterizedJob abstractProject = (ParameterizedJobMixIn.ParameterizedJob) job;
if (job instanceof ParameterizedJobMixIn.ParameterizedJob abstractProject) {

Check warning on line 207 in src/main/java/com/dabsquared/gitlabjenkins/trigger/handler/push/OpenMergeRequestPushHookTriggerHandler.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 62-207 are not covered by tests
if (abstractProject.getQuietPeriod() > projectBuildDelay) {
projectBuildDelay = abstractProject.getQuietPeriod();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ private URIish getFirstRepoURL(List<RemoteConfig> repositories) {
private GitSCM getGitSCM(SCMTriggerItem item) {
if (item != null) {
for (SCM scm : item.getSCMs()) {
if (scm instanceof GitSCM) {
return (GitSCM) scm;
if (scm instanceof GitSCM gitSCM) {
return gitSCM;

Check warning on line 160 in src/main/java/com/dabsquared/gitlabjenkins/trigger/label/ProjectLabelsProvider.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 159-160 are not covered by tests
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public static void updateCommitStatus(
current_client, gitLabBranchBuild.getProjectId(), gitLabBranchBuild.getRevisionHash())) {
LOGGER.log(
Level.INFO,
String.format("Updating build '%s' to '%s'", gitLabBranchBuild.getProjectId(), state));
"Updating build '%s' to '%s'".formatted(gitLabBranchBuild.getProjectId(), state));
current_client.changeBuildStatus(
gitLabBranchBuild.getProjectId(),
gitLabBranchBuild.getRevisionHash(),
Expand All @@ -111,9 +111,8 @@ public static void updateCommitStatus(
e.getMessage());
LOGGER.log(
Level.SEVERE,
String.format(
"Failed to update GitLab commit status for project '%s'",
gitLabBranchBuild.getProjectId()),
"Failed to update GitLab commit status for project '%s'"
.formatted(gitLabBranchBuild.getProjectId()),
e);
}
}
Expand All @@ -138,8 +137,7 @@ private static void println(TaskListener listener, String message) {

private static void printf(TaskListener listener, String message, Object... args) {
if (listener == null) {
LOGGER.log(
Level.FINE, "failed to print message {0} due to null TaskListener", String.format(message, args));
LOGGER.log(Level.FINE, "failed to print message {0} due to null TaskListener", message.formatted(args));

Check warning on line 140 in src/main/java/com/dabsquared/gitlabjenkins/util/CommitStatusUpdater.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 140 is not covered by tests
} else {
listener.getLogger().printf(message, args);
}
Expand All @@ -152,7 +150,7 @@ private static boolean existsCommit(GitLabClient client, String gitlabProjectId,
} catch (NotFoundException e) {
LOGGER.log(
Level.FINE,
String.format("Project (%s) and commit (%s) combination not found", gitlabProjectId, commitHash));
"Project (%s) and commit (%s) combination not found".formatted(gitlabProjectId, commitHash));
return false;
}
}
Expand Down Expand Up @@ -215,12 +213,12 @@ private static List<GitLabBranchBuild> retrieveGitlabProjectIds(Run<?, ?> build,
final SCMRevision scmRevision = scmRevisionAction.getRevision();

String scmRevisionHash = null;
if (scmRevision instanceof AbstractGitSCMSource.SCMRevisionImpl) {
if (scmRevision instanceof AbstractGitSCMSource.SCMRevisionImpl impl) {

Check warning on line 216 in src/main/java/com/dabsquared/gitlabjenkins/util/CommitStatusUpdater.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 216 is only partially covered, one branch is missing
if (scmRevision == null) {
LOGGER.log(Level.INFO, "Build does not contain SCM revision object.");
return result;
}
scmRevisionHash = ((AbstractGitSCMSource.SCMRevisionImpl) scmRevision).getHash();
scmRevisionHash = impl.getHash();
if (scmRevisionHash == null) {
LOGGER.log(Level.INFO, "Build does not contain SCM revision hash.");
return result;
Expand Down Expand Up @@ -284,8 +282,7 @@ private static void addGitLabBranchBuild(
} catch (WebApplicationException | ProcessingException e) {
LOGGER.log(
Level.SEVERE,
String.format(
"Failed to retrieve projectId for project '%s'", projectNameWithNameSpace),
"Failed to retrieve projectId for project '%s'".formatted(projectNameWithNameSpace),

Check warning on line 285 in src/main/java/com/dabsquared/gitlabjenkins/util/CommitStatusUpdater.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 285 is not covered by tests
e);
}
}
Expand All @@ -299,12 +296,11 @@ private static void addGitLabBranchBuild(

private static List<GitLabBranchBuild> findBuildsFromUpstreamCauses(List<Cause> causes) {
for (Cause cause : causes) {
if (cause instanceof UpstreamCause) {
if (cause instanceof UpstreamCause upstreamCause) {

Check warning on line 299 in src/main/java/com/dabsquared/gitlabjenkins/util/CommitStatusUpdater.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 299 is only partially covered, one branch is missing
List<Cause> upCauses =
((UpstreamCause) cause).getUpstreamCauses(); // Non null, returns empty list when none are set
upstreamCause.getUpstreamCauses(); // Non null, returns empty list when none are set
for (Cause upCause : upCauses) {
if (upCause instanceof GitLabWebHookCause) {
GitLabWebHookCause gitlabCause = (GitLabWebHookCause) upCause;
if (upCause instanceof GitLabWebHookCause gitlabCause) {
return Collections.singletonList(new GitLabBranchBuild(
gitlabCause.getData().getSourceProjectId().toString(),
gitlabCause.getData().getLastCommit()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ public static String retrieveProjectId(GitLabClient client, String remoteUrl) th
return matcher.group("projectId");
} else {
throw new ProjectIdResolutionException(
String.format("Failed to retrieve GitLab projectId for %s", remoteUrl));
"Failed to retrieve GitLab projectId for %s".formatted(remoteUrl));
}
} catch (URISyntaxException e) {
throw new ProjectIdResolutionException(
String.format("Failed to retrieve GitLab projectId for %s", remoteUrl), e);
"Failed to retrieve GitLab projectId for %s".formatted(remoteUrl), e);

Check warning on line 45 in src/main/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtil.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 41-45 are not covered by tests
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ private WebHookAction resolveAction(Item project, String restOfPath, StaplerRequ
if (method.equals("POST")) {
return onPost(project, request);
} else if (method.equals("GET")) {
if (project instanceof Job<?, ?>) {
return onGet((Job<?, ?>) project, restOfPath, request);
if (project instanceof Job<?, ?> job) {

Check warning on line 67 in src/main/java/com/dabsquared/gitlabjenkins/webhook/ActionResolver.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 67 is only partially covered, one branch is missing
return onGet(job, restOfPath, request);
} else {
LOGGER.log(Level.FINE, "GET is not supported for this project {0}", project.getName());
return new NoopAction();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,8 @@ private void checkPermission(Permission permission, Item project) {
Objects.requireNonNull(Jenkins.get().getDescriptor(GitLabConnectionConfig.class)))
.isUseAuthenticatedEndpoint()) {
if (!project.getACL().hasPermission(authentication, permission)) {
String message = String.format(
"%s is missing the %s/%s permission",
authentication.getName(), permission.group.title, permission.name);
String message = "%s is missing the %s/%s permission"
.formatted(authentication.getName(), permission.group.title, permission.name);
LOGGER.finest("Unauthorized (Did you forget to add API Token to the web hook ?)");
throw HttpResponses.errorWithoutStack(403, message);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ public SCMSourceOwnerNotifier(Authentication authentication) {

public void run() {
for (SCMSource scmSource : ((SCMSourceOwner) project).getSCMSources()) {
if (scmSource instanceof AbstractGitSCMSource) {
AbstractGitSCMSource gitSCMSource = (AbstractGitSCMSource) scmSource;
if (scmSource instanceof AbstractGitSCMSource gitSCMSource) {

Check warning on line 111 in src/main/java/com/dabsquared/gitlabjenkins/webhook/build/PushBuildAction.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 111 is only partially covered, one branch is missing
try {
if (new URIish(gitSCMSource.getRemote()).equals(new URIish(gitSCMSource.getRemote()))) {
if (SCMTrait.find(gitSCMSource.getTraits(), IgnoreOnPushNotificationTrait.class) == null) {
Expand Down Expand Up @@ -139,9 +138,8 @@ private void checkPermission(Permission permission) {
if (gitlabConfig != null) {
if (gitlabConfig.isUseAuthenticatedEndpoint()) {
if (!project.getACL().hasPermission(authentication, permission)) {
String message = String.format(
"%s is missing the %s/%s permission",
authentication.getName(), permission.group.title, permission.name);
String message = "%s is missing the %s/%s permission"
.formatted(authentication.getName(), permission.group.title, permission.name);
LOGGER.finest("Unauthorized, cannot start indexing on SCMSourceOwner object");
throw HttpResponses.errorWithoutStack(403, message);
}
Expand Down
Loading

0 comments on commit 5018cec

Please sign in to comment.