diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java index 19f04f0168..fd15af1a76 100644 --- a/core/src/main/java/hudson/ClassicPluginStrategy.java +++ b/core/src/main/java/hudson/ClassicPluginStrategy.java @@ -621,15 +621,6 @@ public class ClassicPluginStrategy implements PluginStrategy { return transientDependencies; } -// public List getDependencyPluginWrappers() { -// List r = new ArrayList(); -// for (Dependency d : dependencies) { -// PluginWrapper w = pluginManager.getPlugin(d.shortName); -// if (w!=null) r.add(w); -// } -// return r; -// } - @Override protected Class findClass(String name) throws ClassNotFoundException { if (PluginManager.FAST_LOOKUP) { diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 6756715726..d49e49a358 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -1685,7 +1685,7 @@ public class Functions { if (Util.isOverridden(Throwable.class, t.getClass(), "printStackTrace", PrintWriter.class)) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); - s.append(sw.toString()); + s.append(sw); return; } Throwable lower = t.getCause(); diff --git a/core/src/main/java/hudson/Launcher.java b/core/src/main/java/hudson/Launcher.java index 9baa3992fa..3bc5f5ca51 100644 --- a/core/src/main/java/hudson/Launcher.java +++ b/core/src/main/java/hudson/Launcher.java @@ -813,7 +813,7 @@ public abstract class Launcher { } else buf.append(c); } - listener.getLogger().println(buf.toString()); + listener.getLogger().println(buf); listener.getLogger().flush(); } diff --git a/core/src/main/java/hudson/WebAppMain.java b/core/src/main/java/hudson/WebAppMain.java index 6eab71e566..1f88bae7cb 100644 --- a/core/src/main/java/hudson/WebAppMain.java +++ b/core/src/main/java/hudson/WebAppMain.java @@ -341,7 +341,7 @@ public class WebAppMain implements ServletContextListener { */ private void recordBootAttempt(File home) { try (OutputStream o=Files.newOutputStream(BootFailure.getBootFailureFile(home).toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { - o.write((new Date().toString() + System.getProperty("line.separator", "\n")).getBytes()); + o.write((new Date() + System.getProperty("line.separator", "\n")).getBytes()); } catch (IOException | InvalidPathException e) { LOGGER.log(WARNING, "Failed to record boot attempts",e); } diff --git a/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java b/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java index c3499035a7..aa8d781032 100644 --- a/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java +++ b/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java @@ -76,27 +76,19 @@ public final class MemoryUsageMonitor extends PeriodicWork { private void update() { long used = 0; long max = 0; -// long cur = 0; for (MemoryPoolMXBean pool : pools) { MemoryUsage usage = pool.getCollectionUsage(); if(usage==null) continue; // not available used += usage.getUsed(); max += usage.getMax(); - -// usage = pool.getUsage(); -// if(usage==null) continue; // not available -// cur += usage.getUsed(); } // B -> KB used /= 1024; max /= 1024; -// cur /= 1024; this.used.update(used); this.max.update(max); -// -// return String.format("%d/%d/%d (%d%%)",used,cur,max,used*100/max); } /** diff --git a/core/src/main/java/hudson/diagnosis/OldDataMonitor.java b/core/src/main/java/hudson/diagnosis/OldDataMonitor.java index 6345dff0c5..fa43d35890 100644 --- a/core/src/main/java/hudson/diagnosis/OldDataMonitor.java +++ b/core/src/main/java/hudson/diagnosis/OldDataMonitor.java @@ -274,7 +274,7 @@ public class OldDataMonitor extends AdministrativeMonitor { @Override public String toString() { - return min==null ? "" : min.toString() + (single ? "" : " - " + max.toString()); + return min==null ? "" : min + (single ? "" : " - " + max.toString()); } /** diff --git a/core/src/main/java/hudson/init/TaskMethodFinder.java b/core/src/main/java/hudson/init/TaskMethodFinder.java index c23aa88f76..06702e4ea8 100644 --- a/core/src/main/java/hudson/init/TaskMethodFinder.java +++ b/core/src/main/java/hudson/init/TaskMethodFinder.java @@ -84,7 +84,7 @@ abstract class TaskMethodFinder extends TaskBuilder { c.getClassLoader().loadClass(c.getPackage().getName() + ".Messages")); return rb.format(key); } catch (ClassNotFoundException x) { - LOGGER.log(WARNING, "Failed to load "+x.getMessage()+" for "+e.toString(),x); + LOGGER.log(WARNING, "Failed to load "+x.getMessage()+" for "+ e,x); return key; } catch (MissingResourceException x) { LOGGER.log(WARNING, "Could not find key '" + key + "' in " + c.getPackage().getName() + ".Messages", x); diff --git a/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java b/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java index 2eaec5326f..4241d5a5e8 100644 --- a/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java +++ b/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java @@ -32,9 +32,7 @@ public class InstallUncaughtExceptionHandler { @Initializer public static void init(final Jenkins j) throws IOException { - CompressionFilter.setUncaughtExceptionHandler(j.servletContext, (e, context, req, rsp) -> { - handleException(j, e, req, rsp, 500); - }); + CompressionFilter.setUncaughtExceptionHandler(j.servletContext, (e, context, req, rsp) -> handleException(j, e, req, rsp, 500)); try { Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); LOGGER.log(Level.FINE, "Successfully installed a global UncaughtExceptionHandler."); diff --git a/core/src/main/java/hudson/model/BuildTimelineWidget.java b/core/src/main/java/hudson/model/BuildTimelineWidget.java index 717052e5bf..66b5f3c1d9 100644 --- a/core/src/main/java/hudson/model/BuildTimelineWidget.java +++ b/core/src/main/java/hudson/model/BuildTimelineWidget.java @@ -61,16 +61,13 @@ public class BuildTimelineWidget { public TimelineEventList doData(StaplerRequest req, @QueryParameter long min, @QueryParameter long max) throws IOException { TimelineEventList result = new TimelineEventList(); - for (Run r : builds.byTimestamp(min,max)) { + for (Run r : builds.byTimestamp(min,max)) { Event e = new Event(); e.start = new Date(r.getStartTimeInMillis()); e.end = new Date(r.getStartTimeInMillis()+r.getDuration()); // due to SimileAjax.HTML.deEntify (in simile-ajax-bundle.js), "<" are transformed back to "<", but not the "<"; // to protect against XSS e.title = Util.escape(r.getFullDisplayName()).replace("<", "<"); - // what to put in the description? - // e.description = "Longish description of event "+r.getFullDisplayName(); - // e.durationEvent = true; e.link = req.getContextPath()+'/'+r.getUrl(); BallColor c = r.getIconColor(); e.color = String.format("#%06X",c.getBaseColor().darker().getRGB()&0xFFFFFF); diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java index ae53118c02..dc43184026 100644 --- a/core/src/main/java/hudson/model/Executor.java +++ b/core/src/main/java/hudson/model/Executor.java @@ -417,7 +417,7 @@ public class Executor extends Thread implements ModelObject { } } - setName(getName() + " : executing " + executable.toString()); + setName(getName() + " : executing " + executable); Authentication auth = workUnit.context.item.authenticate2(); LOGGER.log(FINE, "{0} is now executing {1} as {2}", new Object[] {getName(), executable, auth}); if (LOGGER.isLoggable(FINE) && auth.equals(ACL.SYSTEM2)) { // i.e., unspecified diff --git a/core/src/main/java/hudson/model/Fingerprint.java b/core/src/main/java/hudson/model/Fingerprint.java index e31483e070..357232edf2 100644 --- a/core/src/main/java/hudson/model/Fingerprint.java +++ b/core/src/main/java/hudson/model/Fingerprint.java @@ -374,25 +374,6 @@ public class Fingerprint implements ModelObject, Saveable { }; } -// /** -// * List up builds. -// */ -// public ,R extends Run> Iterable listBuilds(final J job) { -// return new Iterable() { -// public Iterator iterator() { -// return new Iterators.FilterIterator(new AdaptedIterator(listNumbers().iterator()) { -// protected R adapt(Integer n) { -// return job.getBuildByNumber(n); -// } -// }) { -// protected boolean filter(R r) { -// return r!=null; -// } -// }; -// } -// }; -// } - /** * List all numbers in this range set in the descending order. */ diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java index 4c038af5cd..04efbb5f7d 100644 --- a/core/src/main/java/hudson/model/Job.java +++ b/core/src/main/java/hudson/model/Job.java @@ -1499,8 +1499,6 @@ public abstract class Job, RunT extends Run implements super(self()); } - // this will never work because Descriptor and Describable are the same thing. -// protected PageDecorator() { -// } @Override public final Descriptor getDescriptor() { diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java index 8a1f743402..58c842dd8f 100644 --- a/core/src/main/java/hudson/model/Run.java +++ b/core/src/main/java/hudson/model/Run.java @@ -1331,28 +1331,6 @@ public abstract class Run ,RunT extends Run names = new HashSet(); -// for (String[] token : tokens) { -// if(!names.add(combineLast(token,n))) -// continue OUTER; // collision. Increase n and try again -// } -// -// // this n successfully disambiguates -// for (int i = 0; i < tokens.length; i++) { -// String[] token = tokens[i]; -// get(i).displayPath = combineLast(token,n); -// } -// return; -// } - -// // it's impossible to get here, as that means -// // we have the same artifacts archived twice, but be defensive -// for (Artifact a : this) -// a.displayPath = a.relativePath; } /** diff --git a/core/src/main/java/hudson/model/Slave.java b/core/src/main/java/hudson/model/Slave.java index 17079a9f2c..7818fa7af3 100644 --- a/core/src/main/java/hudson/model/Slave.java +++ b/core/src/main/java/hudson/model/Slave.java @@ -206,9 +206,6 @@ public abstract class Slave extends Node implements Serializable { if (name.equals("")) throw new FormException(Messages.Slave_InvalidConfig_NoName(), null); -// if (remoteFS.equals("")) -// throw new FormException(Messages.Slave_InvalidConfig_NoRemoteDir(name), null); - if (this.numExecutors<=0) throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null); } diff --git a/core/src/main/java/hudson/model/TreeView.java b/core/src/main/java/hudson/model/TreeView.java index 00191fc97a..8c9543f15a 100644 --- a/core/src/main/java/hudson/model/TreeView.java +++ b/core/src/main/java/hudson/model/TreeView.java @@ -97,19 +97,11 @@ public class TreeView extends View implements ViewGroup { @Override public synchronized List getItems() { return Jenkins.get().getItems(); -// List items = new ArrayList(jobNames.size()); -// for (String name : jobNames) { -// TopLevelItem item = Hudson.getInstance().getItem(name); -// if(item!=null) -// items.add(item); -// } -// return items; } @Override public boolean contains(TopLevelItem item) { return true; -// return jobNames.contains(item.getName()); } @Override diff --git a/core/src/main/java/hudson/model/queue/MappingWorksheet.java b/core/src/main/java/hudson/model/queue/MappingWorksheet.java index cced8c0ac8..d60809b2d0 100644 --- a/core/src/main/java/hudson/model/queue/MappingWorksheet.java +++ b/core/src/main/java/hudson/model/queue/MappingWorksheet.java @@ -173,12 +173,6 @@ public class MappingWorksheet { public class WorkChunk extends ReadOnlyList { public final int index; - // the main should be always at position 0 -// /** -// * This chunk includes {@linkplain WorkUnit#isMainWork() the main work unit}. -// */ -// public final boolean isMain; - /** * If this task needs to be run on a node with a particular label, * return that {@link Label}. Otherwise null, indicating diff --git a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java index 3861bfca21..e773688839 100644 --- a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java +++ b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java @@ -194,8 +194,6 @@ public abstract class AbstractNodeMonitorDescriptor extends Descriptor0) buf.append(','); -// buf.append(l); -// } -// return buf.toString(); int fc = failureCount(); if(fc>0) return Messages.ResponseTimeMonitor_TimeOut(fc); diff --git a/core/src/main/java/hudson/scm/ChangeLogSet.java b/core/src/main/java/hudson/scm/ChangeLogSet.java index 135869989b..c78edcba8d 100644 --- a/core/src/main/java/hudson/scm/ChangeLogSet.java +++ b/core/src/main/java/hudson/scm/ChangeLogSet.java @@ -253,7 +253,7 @@ public abstract class ChangeLogSet implements Iter } catch(Exception e) { LOGGER.info("ChangeLogAnnotator " + a.toString() + " failed to annotate message '" + getMsg() + "'; " + e.getMessage()); } catch(Error e) { - LOGGER.severe("ChangeLogAnnotator " + a.toString() + " failed to annotate message '" + getMsg() + "'; " + e.getMessage()); + LOGGER.severe("ChangeLogAnnotator " + a + " failed to annotate message '" + getMsg() + "'; " + e.getMessage()); } return markup.toString(false); diff --git a/core/src/main/java/hudson/security/BasicAuthenticationFilter.java b/core/src/main/java/hudson/security/BasicAuthenticationFilter.java index 836ddd5f1d..d481260c3a 100644 --- a/core/src/main/java/hudson/security/BasicAuthenticationFilter.java +++ b/core/src/main/java/hudson/security/BasicAuthenticationFilter.java @@ -178,20 +178,6 @@ public class BasicAuthenticationFilter implements Filter { rsp.setHeader("Location",path); } - //public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - // HttpServletRequest req = (HttpServletRequest) request; - // String authorization = req.getHeader("Authorization"); - // - // String path = req.getServletPath(); - // if(authorization==null || req.getUserPrincipal()!=null || path.startsWith("/secured/")) { - // chain.doFilter(request,response); - // } else { - // if(req.getQueryString()!=null) - // path += req.getQueryString(); - // ((HttpServletResponse)response).sendRedirect(req.getContextPath()+"/secured"+path); - // } - //} - @Override public void destroy() { } diff --git a/core/src/main/java/hudson/util/ChunkedInputStream.java b/core/src/main/java/hudson/util/ChunkedInputStream.java index 491e8885fa..b934fd7af9 100644 --- a/core/src/main/java/hudson/util/ChunkedInputStream.java +++ b/core/src/main/java/hudson/util/ChunkedInputStream.java @@ -284,25 +284,6 @@ public class ChunkedInputStream extends InputStream { private void parseTrailerHeaders() throws IOException { // I feel lazy. No trailing header support readCRLF(); - -// Header[] footers = null; -// try { -// String charset = "US-ASCII"; -// if (this.method != null) { -// charset = this.method.getParams().getHttpElementCharset(); -// } -// footers = HttpParser.parseHeaders(in, charset); -// } catch(HttpException e) { -// LOG.error("Error parsing trailer headers", e); -// IOException ioe = new IOException(e.getMessage()); -// ExceptionUtil.initCause(ioe, e); -// throw ioe; -// } -// if (this.method != null) { -// for (int i = 0; i < footers.length; i++) { -// this.method.addResponseFooter(footers[i]); -// } -// } } /** diff --git a/core/src/main/java/hudson/util/FormFieldValidator.java b/core/src/main/java/hudson/util/FormFieldValidator.java index f3e78b1292..29ae0eb8d4 100644 --- a/core/src/main/java/hudson/util/FormFieldValidator.java +++ b/core/src/main/java/hudson/util/FormFieldValidator.java @@ -567,10 +567,8 @@ public abstract class FormFieldValidator { public void validate(File fexe) { try { self.checkExecutable(fexe); - } catch (IOException ioe) { - exceptions[0] = ioe; - } catch (ServletException se) { - exceptions[0] = se; + } catch (IOException | ServletException ex) { + exceptions[0] = ex; } } }); diff --git a/core/src/main/java/hudson/util/ProcessTree.java b/core/src/main/java/hudson/util/ProcessTree.java index 8bcaf49a5f..29435b931f 100644 --- a/core/src/main/java/hudson/util/ProcessTree.java +++ b/core/src/main/java/hudson/util/ProcessTree.java @@ -1691,9 +1691,6 @@ public abstract class ProcessTree implements Iterable, IProcessTree, for( int base=0; base, IProcessTree, return new Remote(this, getChannelForSerialization()); } -// public static void main(String[] args) { -// // dump everything -// LOGGER.setLevel(Level.ALL); -// ConsoleHandler h = new ConsoleHandler(); -// h.setLevel(Level.ALL); -// LOGGER.addHandler(h); -// -// Solaris killer = (Solaris)get(); -// Solaris.SolarisSystem s = killer.createSystem(); -// Solaris.SolarisProcess p = s.get(Integer.parseInt(args[0])); -// System.out.println(p.getEnvVars()); -// -// if(args.length==2) -// p.kill(); -// } - /* On MacOS X, there's no procfs instead you'd do it with the sysctl diff --git a/core/src/main/java/hudson/util/SecretRewriter.java b/core/src/main/java/hudson/util/SecretRewriter.java index ffb417a781..0122503366 100644 --- a/core/src/main/java/hudson/util/SecretRewriter.java +++ b/core/src/main/java/hudson/util/SecretRewriter.java @@ -110,7 +110,7 @@ public class SecretRewriter { copied = eidx; } buf.append(line.substring(copied)); - out.println(buf.toString()); + out.println(buf); } } diff --git a/core/src/main/java/jenkins/fingerprints/FingerprintStorage.java b/core/src/main/java/jenkins/fingerprints/FingerprintStorage.java index d92bbf4c22..f447ed378e 100644 --- a/core/src/main/java/jenkins/fingerprints/FingerprintStorage.java +++ b/core/src/main/java/jenkins/fingerprints/FingerprintStorage.java @@ -114,7 +114,7 @@ public abstract class FingerprintStorage extends AbstractDescribableImpl> whenFileIsCopied100TimesConcurrently(final File file) throws InterruptedException { List> r = new ArrayList<>(); for (int i=0; i<100; i++) { - r.add(new Callable() { - @Override - public Integer call() throws Exception { - class Sink extends OutputStream { - private Exception closed; - private final AtomicInteger count = new AtomicInteger(); + r.add(() -> { + class Sink extends OutputStream { + private Exception closed; + private final AtomicInteger count = new AtomicInteger(); - private void checkNotClosed() throws IOException { - if (closed != null) - throw new IOException(closed); - } - - @Override - public void write(int b) throws IOException { - count.incrementAndGet(); - checkNotClosed(); - } - - @Override - public void write(byte[] b) throws IOException { - count.addAndGet(b.length); - checkNotClosed(); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - count.addAndGet(len); - checkNotClosed(); - } - - @Override - public void close() throws IOException { - closed = new Exception(); - //if (size!=count) - // fail(); - } + private void checkNotClosed() throws IOException { + if (closed != null) + throw new IOException(closed); } - FilePath f = new FilePath(channels.french, file.getPath()); - Sink sink = new Sink(); - f.copyTo(sink); - return sink.count.get(); + @Override + public void write(int b) throws IOException { + count.incrementAndGet(); + checkNotClosed(); + } + + @Override + public void write(byte[] b) throws IOException { + count.addAndGet(b.length); + checkNotClosed(); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + count.addAndGet(len); + checkNotClosed(); + } + + @Override + public void close() throws IOException { + closed = new Exception(); + } } + + FilePath f = new FilePath(channels.french, file.getPath()); + Sink sink = new Sink(); + f.copyTo(sink); + return sink.count.get(); }); } @@ -789,12 +784,8 @@ public class FilePathTest { File f = temp.newFolder("folder"); FilePath fp = new FilePath(f); int invalidMode = 01770; // Full permissions for owner and group plus sticky bit. - try { - chmodAndMode(fp, invalidMode); - fail("Setting sticky bit should fail"); - } catch (IOException e) { - assertEquals("Invalid mode: " + invalidMode, e.getMessage()); - } + final IOException e = assertThrows("Setting sticky bit should fail", IOException.class, () -> chmodAndMode(fp, invalidMode)); + assertEquals("Invalid mode: " + invalidMode, e.getMessage()); } private int chmodAndMode(FilePath path, int mode) throws Exception { diff --git a/core/src/test/java/hudson/PluginManagerTest.java b/core/src/test/java/hudson/PluginManagerTest.java index d4080da9af..5d460ae7f0 100644 --- a/core/src/test/java/hudson/PluginManagerTest.java +++ b/core/src/test/java/hudson/PluginManagerTest.java @@ -48,7 +48,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.StringContains.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests of {@link PluginManager}. @@ -81,14 +81,11 @@ public class PluginManagerTest { "\n"; PluginManager pluginManager = new LocalPluginManager(Util.createTempDir()); - try { - pluginManager.parseRequestedPlugins(new StringInputStream(evilXML)); - fail("XML contains an external entity, but no exception was thrown."); - } - catch (IOException ex) { - assertThat(ex.getCause(), instanceOf(SAXException.class)); - assertThat(ex.getCause().getMessage(), containsString("Refusing to resolve entity with publicId(null) and systemId (file:///)")); - } + final IOException ex = assertThrows(IOException.class, + () -> pluginManager.parseRequestedPlugins(new StringInputStream(evilXML)), + "XML contains an external entity, but no exception was thrown."); + assertThat(ex.getCause(), instanceOf(SAXException.class)); + assertThat(ex.getCause().getMessage(), containsString("Refusing to resolve entity with publicId(null) and systemId (file:///)")); } @Test diff --git a/core/src/test/java/hudson/PluginWrapperTest.java b/core/src/test/java/hudson/PluginWrapperTest.java index 5fc7795de4..58e896cfcf 100644 --- a/core/src/test/java/hudson/PluginWrapperTest.java +++ b/core/src/test/java/hudson/PluginWrapperTest.java @@ -13,7 +13,6 @@ import jenkins.model.Jenkins; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.jvnet.hudson.test.Issue; @@ -22,8 +21,8 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -65,47 +64,35 @@ public class PluginWrapperTest { @Test public void jenkinsCoreTooOld() { PluginWrapper pw = pluginWrapper("fake").requiredCoreVersion("3.0").buildLoaded(); - try { - pw.resolvePluginDependencies(); - fail(); - } catch (IOException ex) { - assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required"); - } + + final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies); + assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required"); } @Test public void dependencyNotInstalled() { PluginWrapper pw = pluginWrapper("dependee").deps("dependency:42").buildLoaded(); - try { - pw.resolvePluginDependencies(); - fail(); - } catch (IOException ex) { - assertContains(ex, "Failed to load: dependee (42)", "Plugin is missing: dependency (42)"); - } + + final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies); + assertContains(ex, "Failed to load: dependee (42)", "Plugin is missing: dependency (42)"); } @Test public void dependencyOutdated() { pluginWrapper("dependency").version("3").buildLoaded(); PluginWrapper pw = pluginWrapper("dependee").deps("dependency:5").buildLoaded(); - try { - pw.resolvePluginDependencies(); - fail(); - } catch (IOException ex) { - assertContains(ex, "Failed to load: dependee (42)", "Update required: dependency (3) to be updated to 5 or higher"); - } + + final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies); + assertContains(ex, "Failed to load: dependee (42)", "Update required: dependency (3) to be updated to 5 or higher"); } @Test public void dependencyFailedToLoad() { pluginWrapper("dependency").version("5").buildFailed(); PluginWrapper pw = pluginWrapper("dependee").deps("dependency:3").buildLoaded(); - try { - pw.resolvePluginDependencies(); - fail(); - } catch (IOException ex) { - assertContains(ex, "Failed to load: dependee (42)", "Failed to load: dependency (5)"); - } + + final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies); + assertContains(ex, "Failed to load: dependee (42)", "Failed to load: dependency (5)"); } private void assertContains(Throwable ex, String... patterns) { @@ -123,18 +110,15 @@ public class PluginWrapperTest { private final HashMap plugins = new HashMap<>(); private final PluginManager pm = mock(PluginManager.class); { - when(pm.getPlugin(any(String.class))).thenAnswer(new Answer() { - @Override public PluginWrapper answer(InvocationOnMock invocation) throws Throwable { - return plugins.get(invocation.getArguments()[0]); - } - }); + when(pm.getPlugin(any(String.class))).thenAnswer((Answer) invocation -> plugins.get(invocation.getArguments()[0])); } + private final class PluginWrapperBuilder { - private String name; + private final String name; private String version = "42"; private String requiredCoreVersion = "1.0"; - private List deps = new ArrayList<>(); - private List optDeps = new ArrayList<>(); + private final List deps = new ArrayList<>(); + private final List optDeps = new ArrayList<>(); private PluginWrapperBuilder(String name) { this.name = name; @@ -157,13 +141,6 @@ public class PluginWrapperTest { return this; } - public PluginWrapperBuilder optDeps(String... optDeps) { - for (String dep: optDeps) { - this.optDeps.add(new PluginWrapper.Dependency(dep)); - } - return this; - } - private PluginWrapper buildLoaded() { PluginWrapper pw = build(); plugins.put(name, pw); diff --git a/core/src/test/java/hudson/UtilTest.java b/core/src/test/java/hudson/UtilTest.java index 2222543c0f..9ab683838c 100644 --- a/core/src/test/java/hudson/UtilTest.java +++ b/core/src/test/java/hudson/UtilTest.java @@ -599,9 +599,7 @@ public class UtilTest { @Test public void ifOverriddenFailure() { - AbstractMethodError error = Assert.assertThrows(AbstractMethodError.class, () -> { - Util.ifOverridden(() -> true, BaseClass.class, DerivedClassFailure.class, "method"); - }); + AbstractMethodError error = Assert.assertThrows(AbstractMethodError.class, () -> Util.ifOverridden(() -> true, BaseClass.class, DerivedClassFailure.class, "method")); assertEquals("The class " + DerivedClassFailure.class.getName() + " must override at least one of the BaseClass.method methods", error.getMessage()); } diff --git a/core/src/test/java/hudson/XmlFileTest.java b/core/src/test/java/hudson/XmlFileTest.java index c8d8b9f3c1..e208c48440 100644 --- a/core/src/test/java/hudson/XmlFileTest.java +++ b/core/src/test/java/hudson/XmlFileTest.java @@ -42,7 +42,7 @@ public class XmlFileTest { XmlFile xmlFile = new XmlFile(xs, new File(configUrl.getFile())); if (xmlFile.exists()) { - assertThrows(SAXParseException.class, () -> xmlFile.read()); + assertThrows(SAXParseException.class, xmlFile::read); } } diff --git a/core/src/test/java/hudson/model/ItemsTest.java b/core/src/test/java/hudson/model/ItemsTest.java index 2a7cef9f5d..3bdedd259c 100644 --- a/core/src/test/java/hudson/model/ItemsTest.java +++ b/core/src/test/java/hudson/model/ItemsTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -14,9 +14,9 @@ import static org.mockito.Mockito.when; */ public class ItemsTest { - private static ItemGroup root; - private static ItemGroup foo; - private static ItemGroup foo_bar; + private static ItemGroup root; + private static ItemGroup foo; + private static ItemGroup foo_bar; @BeforeClass public static void itemGroups() { @@ -28,7 +28,6 @@ public class ItemsTest { foo_bar = mock(ItemGroup.class); when(foo_bar.getFullName()).thenReturn("foo/bar"); - } @Test @@ -43,26 +42,14 @@ public class ItemsTest { assertEquals("foo/bar/baz/qux", Items.getCanonicalName(foo_bar, "baz/qux")); assertEquals("foo/baz/qux", Items.getCanonicalName(foo_bar, "../baz/qux")); - try { - Items.getCanonicalName(root, ".."); - fail(); - } catch (IllegalArgumentException ex) { - assertEquals("Illegal relative path '..' within context ''", ex.getMessage()); - } + final IllegalArgumentException ex0 = assertThrows(IllegalArgumentException.class, () -> Items.getCanonicalName(root, "..")); + assertEquals("Illegal relative path '..' within context ''", ex0.getMessage()); - try { - Items.getCanonicalName(foo, "../.."); - fail(); - } catch (IllegalArgumentException ex) { - assertEquals("Illegal relative path '../..' within context 'foo'", ex.getMessage()); - } + final IllegalArgumentException ex1 = assertThrows(IllegalArgumentException.class, () -> Items.getCanonicalName(foo, "../..")); + assertEquals("Illegal relative path '../..' within context 'foo'", ex1.getMessage()); - try { - Items.getCanonicalName(root, "foo/../.."); - fail(); - } catch (IllegalArgumentException ex) { - assertEquals("Illegal relative path 'foo/../..' within context ''", ex.getMessage()); - } + final IllegalArgumentException ex2 = assertThrows(IllegalArgumentException.class, () -> Items.getCanonicalName(root, "foo/../..")); + assertEquals("Illegal relative path 'foo/../..' within context ''", ex2.getMessage()); } @Test diff --git a/core/src/test/java/hudson/model/UpdateCenterTest.java b/core/src/test/java/hudson/model/UpdateCenterTest.java index 2a84fab8d5..8d4ff97f67 100644 --- a/core/src/test/java/hudson/model/UpdateCenterTest.java +++ b/core/src/test/java/hudson/model/UpdateCenterTest.java @@ -10,8 +10,8 @@ import java.util.Locale; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; public class UpdateCenterTest { @@ -52,12 +52,10 @@ public class UpdateCenterTest { @Test public void noChecksums() { - try { - UpdateCenter.verifyChecksums(new MockDownloadJob(null, null, null), buildEntryWithExpectedChecksums(null, null, null), new File("example")); - fail(); - } catch (IOException ex) { - assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage()); - } + final IOException ex = assertThrows(IOException.class, + () -> UpdateCenter.verifyChecksums(new MockDownloadJob(null, null, null), + buildEntryWithExpectedChecksums(null, null, null), new File("example"))); + assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage()); } @Test @@ -69,14 +67,10 @@ public class UpdateCenterTest { @Test public void sha1Mismatch() { - try { - UpdateCenter.verifyChecksums( - new MockDownloadJob(EMPTY_SHA1.replace('k', 'f'), null, null), - buildEntryWithExpectedChecksums(EMPTY_SHA1, null, null), new File("example")); - fail(); - } catch (IOException ex) { - assertTrue(ex.getMessage().contains("does not match expected SHA-1, expected '2jmj7l5rSw0yVb/vlWAYkK/YBwk=', actual '2jmj7l5rSw0yVb/vlWAYfK/YBwf='")); - } + final IOException ex = assertThrows(IOException.class, () -> UpdateCenter.verifyChecksums( + new MockDownloadJob(EMPTY_SHA1.replace('k', 'f'), null, null), + buildEntryWithExpectedChecksums(EMPTY_SHA1, null, null), new File("example"))); + assertTrue(ex.getMessage().contains("does not match expected SHA-1, expected '2jmj7l5rSw0yVb/vlWAYkK/YBwk=', actual '2jmj7l5rSw0yVb/vlWAYfK/YBwf='")); } @Test @@ -95,45 +89,32 @@ public class UpdateCenterTest { @Test public void sha1DoesNotIgnoreCase() { - try { - UpdateCenter.verifyChecksums( - new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, EMPTY_SHA512), - buildEntryWithExpectedChecksums(EMPTY_SHA1.toUpperCase(Locale.US), null, null), new File("example")); - fail(); - } catch (Exception e) { - assertTrue(e.getMessage().contains("does not match expected SHA-1, expected '2JMJ7L5RSW0YVB/VLWAYKK/YBWK=', actual '2jmj7l5rSw0yVb/vlWAYkK/YBwk='")); - } - + final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums( + new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, EMPTY_SHA512), + buildEntryWithExpectedChecksums(EMPTY_SHA1.toUpperCase(Locale.US), null, null), new File("example"))); + assertTrue(ex.getMessage().contains("does not match expected SHA-1, expected '2JMJ7L5RSW0YVB/VLWAYKK/YBWK=', actual '2jmj7l5rSw0yVb/vlWAYkK/YBwk='")); } @Test public void noOverlapForComputedAndProvidedChecksums() { - try { - UpdateCenter.verifyChecksums( - new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, null), - buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("example")); - fail(); - } catch (Exception e) { - assertEquals("Unable to confirm integrity of downloaded file, refusing installation", e.getMessage()); - } + final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums( + new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, null), + buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("example"))); + assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage()); } @Test public void noOverlapForComputedAndProvidedChecksumsForSpecIncompliantJVM() { - try { - UpdateCenter.verifyChecksums( - new MockDownloadJob(EMPTY_SHA1, null, null), - buildEntryWithExpectedChecksums(null, EMPTY_SHA256, EMPTY_SHA512), new File("example")); - fail(); - } catch (Exception e) { - assertEquals("Unable to confirm integrity of downloaded file, refusing installation", e.getMessage()); - } + final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums( + new MockDownloadJob(EMPTY_SHA1, null, null), + buildEntryWithExpectedChecksums(null, EMPTY_SHA256, EMPTY_SHA512), new File("example"))); + assertEquals("Unable to confirm integrity of downloaded file, refusing installation", ex.getMessage()); } - private static String EMPTY_SHA1 = "2jmj7l5rSw0yVb/vlWAYkK/YBwk="; - private static String EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - private static String EMPTY_SHA512 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; + private static final String EMPTY_SHA1 = "2jmj7l5rSw0yVb/vlWAYkK/YBwk="; + private static final String EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + private static final String EMPTY_SHA512 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; private static UpdateSite.Entry buildEntryWithExpectedChecksums(String expectedSHA1, String expectedSHA256, String expectedSHA512) { JSONObject o = new JSONObject(); diff --git a/core/src/test/java/hudson/scheduler/CronTabTest.java b/core/src/test/java/hudson/scheduler/CronTabTest.java index c812b4c651..958b9807ad 100644 --- a/core/src/test/java/hudson/scheduler/CronTabTest.java +++ b/core/src/test/java/hudson/scheduler/CronTabTest.java @@ -33,7 +33,7 @@ import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -265,12 +265,8 @@ public class CronTabTest { compare(new GregorianCalendar(2013, 2, 21, 0, 2), new CronTab("H(0-15)/3 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0))); compare(new GregorianCalendar(2013, 2, 21, 0, 2), new CronTab("H(0-3)/4 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0))); compare(new GregorianCalendar(2013, 2, 21, 1, 2), new CronTab("H(0-3)/4 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 5))); - try { - compare(new GregorianCalendar(2013, 2, 21, 0, 0), new CronTab("H(0-3)/15 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0))); - fail(); - } catch (ANTLRException x) { - // good - } + + assertThrows(ANTLRException.class, () -> compare(new GregorianCalendar(2013, 2, 21, 0, 0), new CronTab("H(0-3)/15 * * * *", Hash.from("junk")).ceil(new GregorianCalendar(2013, 2, 21, 0, 0)))); } @Test public void repeatedHash() throws Exception { @@ -289,21 +285,11 @@ public class CronTabTest { } @Test public void rangeBoundsCheckFailHour() { - try { - new CronTab("H H(12-24) * * *"); - fail(); - } catch (ANTLRException e) { - // ok - } + assertThrows(ANTLRException.class, () -> new CronTab("H H(12-24) * * *")); } @Test public void rangeBoundsCheckFailMinute() { - try { - new CronTab("H(33-66) * * * *"); - fail(); - } catch (ANTLRException e) { - // ok - } + assertThrows(ANTLRException.class, () -> new CronTab("H(33-66) * * * *")); } @Issue("JENKINS-9283") diff --git a/core/src/test/java/jenkins/RemotingJarSignatureTest.java b/core/src/test/java/jenkins/RemotingJarSignatureTest.java index 7bf5ac7264..f6103ec165 100644 --- a/core/src/test/java/jenkins/RemotingJarSignatureTest.java +++ b/core/src/test/java/jenkins/RemotingJarSignatureTest.java @@ -1,6 +1,6 @@ package jenkins; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertNotNull; import hudson.remoting.Channel; import hudson.remoting.Which; @@ -23,8 +23,6 @@ public class RemotingJarSignatureTest { @Test public void testSignature() throws Exception { File jar = Which.jarFile(Channel.class); -// File jar = new File("/home/kohsuke/.m2/repository/org/jenkins-ci/main/remoting/1.421/remoting-1.421.jar"); -// File jar = new File("/home/kohsuke/.m2/repository/org/jenkins-ci/main/remoting/2.0/remoting-2.0.jar"); System.out.println("Verifying "+jar); JarFile myJar = new JarFile(jar,true); @@ -43,9 +41,7 @@ public class RemotingJarSignatureTest { // make sure bits are signed IOUtils.copy(myJar.getInputStream(entry), NullOutputStream.NULL_OUTPUT_STREAM); - if (entry.getCodeSigners()==null) { - fail("No signature for " + name); - } + assertNotNull("No signature for " + name, entry.getCodeSigners()); } } } diff --git a/core/src/test/java/jenkins/util/JenkinsJVMTest.java b/core/src/test/java/jenkins/util/JenkinsJVMTest.java index 206ca39fe2..888c592739 100644 --- a/core/src/test/java/jenkins/util/JenkinsJVMTest.java +++ b/core/src/test/java/jenkins/util/JenkinsJVMTest.java @@ -13,14 +13,14 @@ public class JenkinsJVMTest { @Test public void checkJenkinsJVM_WhenNotInAJenkinsJVM() { - assertThrows(IllegalStateException.class, () -> JenkinsJVM.checkJenkinsJVM()); + assertThrows(IllegalStateException.class, JenkinsJVM::checkJenkinsJVM); } @Test public void checkNotJenkinsJVM_WhenInAJenkinsJVM() { JenkinsJVM.setJenkinsJVM(true); try { - assertThrows(IllegalStateException.class, () -> JenkinsJVM.checkNotJenkinsJVM()); + assertThrows(IllegalStateException.class, JenkinsJVM::checkNotJenkinsJVM); } finally { JenkinsJVM.setJenkinsJVM(false); } diff --git a/core/src/test/java/jenkins/util/VirtualFileTest.java b/core/src/test/java/jenkins/util/VirtualFileTest.java index e2f4d81a45..c28a213b1b 100644 --- a/core/src/test/java/jenkins/util/VirtualFileTest.java +++ b/core/src/test/java/jenkins/util/VirtualFileTest.java @@ -100,7 +100,7 @@ public class VirtualFileTest { VirtualFile hack = root.child("hack"); assertFalse(hack.isFile()); assertFalse(hack.exists()); - assertThrows(FileNotFoundException.class, () -> hack.open()); + assertThrows(FileNotFoundException.class, hack::open); } @Issue("JENKINS-26810")