Skip to content

Commit

Permalink
Require Java 17
Browse files Browse the repository at this point in the history
Updates plugin to LTS that requires Java 17. Applied using
OpenRewrite Java11to17 plugin which updates to use instanceof
pattern matching instead of casting.
  • Loading branch information
slide committed Nov 12, 2024
1 parent 6dd03bf commit 2ece3a2
Show file tree
Hide file tree
Showing 29 changed files with 252 additions and 201 deletions.
11 changes: 6 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>4.88</version>
<version>5.2</version>
<relativePath />
</parent>

Expand Down Expand Up @@ -87,8 +87,9 @@

<properties>
<changelist>999999-SNAPSHOT</changelist>
<gitHubRepo>jenkinsci/email-ext-plugin</gitHubRepo>
<jenkins.version>2.462.3</jenkins.version>
<gitHubRepo>jenkinsci/${project.artifactId}-plugin</gitHubRepo>
<jenkins.baseline>2.479</jenkins.baseline>
<jenkins.version>${jenkins.baseline}.1</jenkins.version>
<hpi.compatibleSinceVersion>2.57.2</hpi.compatibleSinceVersion>
<concurrency>1</concurrency>
<!-- To be removed once Jenkins.MANAGE gets out of beta -->
Expand All @@ -100,8 +101,8 @@
<dependencies>
<dependency>
<groupId>io.jenkins.tools.bom</groupId>
<artifactId>bom-2.440.x</artifactId>
<version>3435.v238d66a_043fb_</version>
<artifactId>bom-2.479.x</artifactId>
<version>3613.v584fca_12cf5c</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Expand Down
9 changes: 6 additions & 3 deletions src/main/java/hudson/plugins/emailext/AttachmentUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serial;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -32,7 +33,9 @@
*/
public class AttachmentUtils implements Serializable {

@Serial
private static final long serialVersionUID = 1L;

private final String attachmentsPattern;

public AttachmentUtils(String attachmentsPattern) {
Expand Down Expand Up @@ -157,7 +160,7 @@ private List<MimeBodyPart> getAttachments(final ExtendedEmailPublisherContext co
try {
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(MimeUtility.encodeText(file.getName()));
attachmentPart.setContentID(String.format("<%s>", file.getName()));
attachmentPart.setContentID("<%s>".formatted(file.getName()));
attachments.add(attachmentPart);
totalAttachmentSize += file.length();
} catch (MessagingException e) {
Expand Down Expand Up @@ -231,9 +234,9 @@ private static void attachSingleLog(
return;
}

if (run instanceof MatrixRun) {
if (run instanceof MatrixRun matrixRun) {
attachment.setFileName("build" + "-"
+ ((MatrixRun) run).getParent().getCombination().toString('-', '-') + "."
+ matrixRun.getParent().getCombination().toString('-', '-') + "."
+ (compress ? "zip" : "log"));
} else {
attachment.setFileName("build." + (compress ? "zip" : "log"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public static String getUserConfiguredEmail(User user) {
Mailer.UserProperty mailProperty = user.getProperty(Mailer.UserProperty.class);
if (mailProperty != null) {
addr = mailProperty.getAddress();
String message = String.format("Resolved %s to %s", user.getId(), addr);
String message = "Resolved %s to %s".formatted(user.getId(), addr);
LOGGER.fine(message);
}
}
Expand Down
25 changes: 14 additions & 11 deletions src/main/java/hudson/plugins/emailext/ExtendedEmailPublisher.java
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,11 @@ public class ExtendedEmailPublisher extends Notifier implements MatrixAggregatab

public static final String DEFAULT_SUBJECT_TEXT = "$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!";

public static final String DEFAULT_BODY_TEXT = "$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS:\n\n"
+ "Check console output at $BUILD_URL to view the results.";
public static final String DEFAULT_BODY_TEXT =
"""
$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS:
Check console output at $BUILD_URL to view the results.""";

public static final String DEFAULT_EMERGENCY_REROUTE_TEXT = "";

Expand Down Expand Up @@ -621,8 +624,8 @@ boolean sendMail(ExtendedEmailPublisherContext context) {
context.getListener().getLogger(),
"Next " + next.getClass().getSimpleName() + " message: "
+ next.getMessage());
if (next instanceof MessagingException) {
next = ((MessagingException) next).getNextException();
if (next instanceof MessagingException exception) {
next = exception.getNextException();
} else {
next = null;
}
Expand All @@ -646,8 +649,8 @@ boolean sendMail(ExtendedEmailPublisherContext context) {
context.getListener().getLogger(),
"Next " + next.getClass().getSimpleName() + " message: "
+ next.getMessage());
if (next instanceof MessagingException) {
next = ((MessagingException) next).getNextException();
if (next instanceof MessagingException exception) {
next = exception.getNextException();
} else {
next = null;
}
Expand Down Expand Up @@ -1146,11 +1149,11 @@ private Multipart addContent(ExtendedEmailPublisherContext context, String chars
if (workspace != null) {
FilePath savedOutput = new FilePath(
workspace,
String.format(
"%s-%s%s",
context.getTrigger().getDescriptor().getDisplayName(),
context.getRun().getId(),
extension));
"%s-%s%s"
.formatted(
context.getTrigger().getDescriptor().getDisplayName(),
context.getRun().getId(),
extension));
savedOutput.write(text, charset);
} else {
context.getListener().getLogger().println("No workspace to save the email to");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ protected void setPublisher(ExtendedEmailPublisher publisher) {
*/
@Deprecated
public AbstractBuild<?, ?> getBuild() {
if (run instanceof AbstractBuild) {
return (AbstractBuild<?, ?>) run;
if (run instanceof AbstractBuild<?, ?> build) {
return build;
}
return null;
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/hudson/plugins/emailext/MailAccount.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item, @QueryPa
}
return result.includeEmptyValue()
.includeMatchingAs(
item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
item instanceof Queue.Task t ? Tasks.getAuthenticationOf(t) : ACL.SYSTEM,
item,
StandardUsernamePasswordCredentials.class,
Collections.emptyList(),
Expand Down Expand Up @@ -170,7 +170,7 @@ public FormValidation doCheckCredentialsId(
if (CredentialsProvider.listCredentials(
StandardUsernamePasswordCredentials.class,
item,
item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
item instanceof Queue.Task t ? Tasks.getAuthenticationOf(t) : ACL.SYSTEM,
null,
CredentialsMatchers.withId(value))
.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,9 @@ public boolean permitsMethod(@NonNull Method method, @NonNull Object receiver, @
// method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (SimpleTemplateScript2
// BUILD_ID)
if (method.getDeclaringClass() == GroovyObject.class
&& receiver instanceof EmailExtScript
&& receiver instanceof EmailExtScript script
&& "invokeMethod".equals(method.getName())
&& args.length > 0) {
EmailExtScript script = (EmailExtScript) receiver;
String name = String.valueOf(args[0]);

for (TokenMacro m : macros) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,14 @@ protected EmailType createMailType(StaplerRequest req, JSONObject formData) {
protected int getNumFailures(Run<?, ?> build) {
AbstractTestResultAction<? extends AbstractTestResultAction<?>> a =
build.getAction(AbstractTestResultAction.class);
if (a instanceof AggregatedTestResultAction) {
if (a instanceof AggregatedTestResultAction action) {
int result = 0;
AggregatedTestResultAction action = (AggregatedTestResultAction) a;
for (ChildReport cr : action.getChildReports()) {
if (cr == null || cr.child == null || cr.child.getParent() == null) {
continue;
}
if (cr.child.getParent().equals(build.getParent())) {
if (cr.result instanceof TestResult) {
TestResult tr = (TestResult) cr.result;
if (cr.result instanceof TestResult tr) {
result += tr.getFailCount();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public List<RecipientProvider> getDefaultRecipientProviders() {
return defaultRecipientProviders;
}

public abstract EmailTrigger createDefault();
public abstract EmailTrigger createDefault() throws FormException;

@SuppressFBWarnings("REC_CATCH_EXCEPTION")
protected EmailTrigger _createDefault() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ protected InputStream getFileInputStream(Run<?, ?> run, FilePath workspace, Stri
}

if (inputStream == null) {
throw new FileNotFoundException(String.format("Managed file '%s' not found", managedFileName));
throw new FileNotFoundException("Managed file '%s' not found".formatted(managedFileName));
}
return inputStream;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ public abstract class EmailExtScript extends Script {
public EmailExtScript() {}

private void populateArgs(Object args, Map<String, String> map, ListMultimap<String, String> multiMap) {
if (args instanceof Object[]) {
Object[] argArray = (Object[]) args;
if (args instanceof Object[] argArray) {
if (argArray.length > 0) {
Map<String, Object> argMap = (Map<String, Object>) argArray[0];
for (Map.Entry<String, Object> entry : argMap.entrySet()) {
Expand Down Expand Up @@ -86,6 +85,6 @@ public Object methodMissing(String name, Object args)
}
}

return String.format("[Could not find content token (check your usage): %s]", name);
return "[Could not find content token (check your usage): %s]".formatted(name);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ private SummarizedTestResult prepareSummarizedTestResult(AbstractTestResultActio
if (failCount == 0) {
result.summary = "All tests passed";
} else {
result.summary = String.format("%d tests failed.", failCount);
result.summary = "%d tests failed.".formatted(failCount);
setMaxLength();
if (maxTests > 0) {
int printSize = 0;
Expand All @@ -141,10 +141,10 @@ private int addTest(SummarizedTestResult result, int printSize, TestResult faile
? StringEscapeUtils.escapeHtml(failedTest.getErrorDetails())
: failedTest.getErrorDetails())
: null;
String name = String.format(
"%s.%s",
failedTest instanceof CaseResult ? ((CaseResult) failedTest).getClassName() : failedTest.getFullName(),
failedTest.getDisplayName());
String name = "%s.%s"
.formatted(
failedTest instanceof CaseResult cr ? cr.getClassName() : failedTest.getFullName(),
failedTest.getDisplayName());
FailedTest t = new FailedTest(name, failedTest.isPassed(), errorDetails, stackTrace);
String testYaml = t.toString();
if (printSize <= maxLength && result.tests.size() < maxTests) {
Expand Down Expand Up @@ -174,9 +174,8 @@ public FailedTest(String name, boolean status, String errorMessage, String stack

@Override
public String toString() {
return String.format(
"Name:%s, Status:%s, Error message: %s, Stack trace:%s",
this.name, this.status, this.errorMessage, this.stackTrace);
return "Name:%s, Status:%s, Error message: %s, Stack trace:%s"
.formatted(this.name, this.status, this.errorMessage, this.stackTrace);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public List<TestResult> getJUnitTestResult() {
/* Maven Project */
List<AggregatedTestResultAction.ChildReport> reportList = action.getChildReports();
for (AggregatedTestResultAction.ChildReport report : reportList) {
if (report.result instanceof hudson.tasks.junit.TestResult) {
result.add((TestResult) report.result);
if (report.result instanceof hudson.tasks.junit.TestResult testResult) {
result.add(testResult);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ public void send(final String format, final Object... args) {
final Debug debug = new Debug();
Run<?, ?> run = context.getRun();

if (run instanceof RunWithSCM) {
Set<User> culprits = ((RunWithSCM<?, ?>) run).getCulprits();
if (run instanceof RunWithSCM<?, ?> cM) {
Set<User> culprits = cM.getCulprits();
RecipientProviderUtilities.addUsers(culprits, context, env, to, cc, bcc, debug);
} else {
List<Run<?, ?>> builds = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public void send(final String format, final Object... args) {
Run<?, ?> build = context.getRun().getPreviousCompletedBuild();

while (users.isEmpty() && build != null) {
if (build instanceof RunWithSCM) {
users.addAll(((RunWithSCM<?, ?>) build).getCulprits());
if (build instanceof RunWithSCM<?, ?> cM) {
users.addAll(cM.getCulprits());
}
users.addAll(RecipientProviderUtilities.getChangeSetAuthors(Collections.singleton(build), debug));
users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(Collections.singleton(build), debug));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public static Set<User> getChangeSetAuthors(final Collection<Run<?, ?>> runs, fi
final Set<User> users = new HashSet<>();
for (final Run<?, ?> run : runs) {
debug.send(" build: %d", run.getNumber());
if (run instanceof RunWithSCM) {
List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = ((RunWithSCM<?, ?>) run).getChangeSets();
if (run instanceof RunWithSCM<?, ?> cM) {
List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = cM.getChangeSets();
for (ChangeLogSet<? extends ChangeLogSet.Entry> changeSet : changeSets) {
addChangeSetUsers(changeSet, users, debug);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public void send(final String format, final Object... args) {
private static List<Run<?, ?>> getUpstreamBuilds(Run<?, ?> build) {
List<Run<?, ?>> upstreams = new ArrayList<>();
for (Cause c : build.getCauses()) {
if (c instanceof Cause.UpstreamCause) {
upstreams.addAll(upstreamCauseToRuns((Cause.UpstreamCause) c));
if (c instanceof Cause.UpstreamCause cause) {
upstreams.addAll(upstreamCauseToRuns(cause));
}
}
return upstreams;
Expand All @@ -73,8 +73,8 @@ public void send(final String format, final Object... args) {
if (r != null) {
upstreams.add(r);
for (Cause c : cause.getUpstreamCauses()) {
if (c instanceof Cause.UpstreamCause) {
upstreams.addAll(upstreamCauseToRuns((Cause.UpstreamCause) c));
if (c instanceof Cause.UpstreamCause upstreamCause) {
upstreams.addAll(upstreamCauseToRuns(upstreamCause));
}
}
}
Expand Down Expand Up @@ -102,8 +102,8 @@ private void addUpstreamCommittersTriggeringBuild(
"Adding upstream committer from job %s with build number %s",
run.getParent().getDisplayName(), run.getNumber());

if (run instanceof RunWithSCM) {
List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = ((RunWithSCM<?, ?>) run).getChangeSets();
if (run instanceof RunWithSCM<?, ?> cM) {
List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = cM.getChangeSets();

for (ChangeLogSet<? extends ChangeLogSet.Entry> changeSet : changeSets) {
for (ChangeLogSet.Entry change : changeSet) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import groovy.lang.GroovyShell;
import hudson.Functions;
import hudson.model.AbstractBuild;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist;
Expand Down Expand Up @@ -77,7 +78,8 @@ public AbstractScriptTrigger(
String attachmentsPattern,
int attachBuildLog,
String contentType,
String triggerScript) {
String triggerScript)
throws Descriptor.FormException {
this(
recipientProviders,
recipientList,
Expand Down Expand Up @@ -232,7 +234,7 @@ private Object evaluate(AbstractBuild<?, ?> build, TaskListener listener) throws
* @throws ObjectStreamException if the object cannot be restored.
* @see <a href="http://download.oracle.com/javase/1.3/docs/guide/serialization/spec/input.doc6.html">The Java Object Serialization Specification</a>
*/
protected Object readResolve() throws ObjectStreamException {
protected Object readResolve() throws ObjectStreamException, Descriptor.FormException {
if (triggerScript != null && secureTriggerScript == null) {
this.secureTriggerScript = new SecureGroovyScript(triggerScript, false, null);
this.secureTriggerScript.configuring(ApprovalContext.create());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.emailext.plugins.EmailTrigger;
import hudson.plugins.emailext.plugins.EmailTriggerDescriptor;
import hudson.plugins.emailext.plugins.RecipientProvider;
Expand Down Expand Up @@ -46,7 +47,8 @@ public PreBuildScriptTrigger(
String attachmentsPattern,
int attachBuildLog,
String contentType,
String triggerScript) {
String triggerScript)
throws Descriptor.FormException {
super(
recipientProviders,
recipientList,
Expand Down Expand Up @@ -108,7 +110,7 @@ public boolean isWatchable() {
}

@Override
public EmailTrigger createDefault() {
public EmailTrigger createDefault() throws Descriptor.FormException {
return new PreBuildScriptTrigger(
defaultRecipientProviders,
"",
Expand Down
Loading

0 comments on commit 2ece3a2

Please sign in to comment.