diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 26d39ea2e7..35befac2e9 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -43,6 +43,10 @@ import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.SecureRandom; @@ -59,7 +63,6 @@ import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.glassfish.tyrus.client.ClientManager; import org.glassfish.tyrus.client.ClientProperties; @@ -326,7 +329,13 @@ public class CLI { @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") private static String readAuthFromFile(String auth) throws IOException { - return FileUtils.readFileToString(new File(auth.substring(1)), Charset.defaultCharset()); + Path path; + try { + path = Paths.get(auth.substring(1)); + } catch (InvalidPathException e) { + throw new IOException(e); + } + return Files.readString(path, Charset.defaultCharset()); } @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") diff --git a/core/src/main/java/hudson/init/impl/InitialUserContent.java b/core/src/main/java/hudson/init/impl/InitialUserContent.java index 81cc279eb9..0e93164574 100644 --- a/core/src/main/java/hudson/init/impl/InitialUserContent.java +++ b/core/src/main/java/hudson/init/impl/InitialUserContent.java @@ -29,11 +29,11 @@ import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; import hudson.Util; import hudson.init.Initializer; import hudson.model.Messages; -import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import jenkins.model.Jenkins; -import org.apache.commons.io.FileUtils; /** * Prepares userContent folder and put a readme if it doesn't exist. @@ -42,10 +42,10 @@ import org.apache.commons.io.FileUtils; public class InitialUserContent { @Initializer(after = JOB_CONFIG_ADAPTED) public static void init(Jenkins h) throws IOException { - File userContentDir = new File(h.getRootDir(), "userContent"); - if (!Files.isDirectory(Util.fileToPath(userContentDir))) { - Util.createDirectories(Util.fileToPath(userContentDir)); - FileUtils.writeStringToFile(new File(userContentDir, "readme.txt"), Messages.Hudson_USER_CONTENT_README() + "\n"); + Path userContentDir = Util.fileToPath(h.getRootDir()).resolve("userContent"); + if (!Files.isDirectory(userContentDir)) { + Util.createDirectories(userContentDir); + Files.writeString(userContentDir.resolve("readme.txt"), Messages.Hudson_USER_CONTENT_README() + System.lineSeparator(), StandardCharsets.UTF_8); } } } diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java index 2fbc1521de..50875f19b8 100644 --- a/core/src/main/java/hudson/model/AbstractItem.java +++ b/core/src/main/java/hudson/model/AbstractItem.java @@ -55,6 +55,8 @@ import hudson.util.Secret; import java.io.File; import java.io.IOException; import java.io.OutputStream; +import java.nio.charset.Charset; +import java.nio.file.Files; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; @@ -78,7 +80,6 @@ import jenkins.model.queue.ItemDeletion; import jenkins.security.NotReallyRoleSensitiveCallable; import jenkins.util.SystemProperties; import jenkins.util.xml.XMLUtils; -import org.apache.commons.io.FileUtils; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; @@ -851,7 +852,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet IOUtils.copy(configFile.getFile(), os); } else { String encoding = configFile.sniffEncoding(); - String xml = FileUtils.readFileToString(configFile.getFile(), encoding); + String xml = Files.readString(Util.fileToPath(configFile.getFile()), Charset.forName(encoding)); Matcher matcher = SECRET_PATTERN.matcher(xml); StringBuffer cleanXml = new StringBuffer(); while (matcher.find()) { diff --git a/core/src/main/java/hudson/triggers/SCMTrigger.java b/core/src/main/java/hudson/triggers/SCMTrigger.java index c469022921..a078cde4ff 100644 --- a/core/src/main/java/hudson/triggers/SCMTrigger.java +++ b/core/src/main/java/hudson/triggers/SCMTrigger.java @@ -57,6 +57,7 @@ import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.nio.charset.Charset; +import java.nio.file.Files; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; @@ -79,7 +80,6 @@ import jenkins.scm.SCMDecisionHandler; import jenkins.triggers.SCMTriggerItem; import jenkins.util.SystemProperties; import net.sf.json.JSONObject; -import org.apache.commons.io.FileUtils; import org.apache.commons.jelly.XMLOutput; import org.apache.commons.lang.StringUtils; import org.jenkinsci.Symbol; @@ -717,7 +717,7 @@ public class SCMTrigger extends Trigger { public SCMTriggerCause(File logFile) throws IOException { // TODO: charset of this log file? - this(FileUtils.readFileToString(logFile)); + this(Files.readString(Util.fileToPath(logFile), Charset.defaultCharset())); } public SCMTriggerCause(String pollingLog) { @@ -743,7 +743,7 @@ public class SCMTrigger extends Trigger { this.run = build; try { BuildAction a = new BuildAction(build); - FileUtils.writeStringToFile(a.getPollingLogFile(), pollingLog); + Files.writeString(Util.fileToPath(a.getPollingLogFile()), pollingLog, Charset.defaultCharset()); build.replaceAction(a); } catch (IOException e) { LOGGER.log(WARNING, "Failed to persist the polling log", e); diff --git a/core/src/main/java/hudson/util/DoubleLaunchChecker.java b/core/src/main/java/hudson/util/DoubleLaunchChecker.java index f42004a1d6..4631b829b0 100644 --- a/core/src/main/java/hudson/util/DoubleLaunchChecker.java +++ b/core/src/main/java/hudson/util/DoubleLaunchChecker.java @@ -28,6 +28,7 @@ import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import hudson.Util; import hudson.init.Initializer; import hudson.triggers.SafeTimerTask; import java.io.File; @@ -35,6 +36,7 @@ import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.nio.charset.Charset; +import java.nio.file.Files; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.logging.Level; @@ -43,7 +45,6 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import jenkins.model.Jenkins; import jenkins.util.Timer; -import org.apache.commons.io.FileUtils; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.interceptor.RequirePOST; @@ -103,7 +104,7 @@ public class DoubleLaunchChecker { long t = timestampFile.lastModified(); if (t != 0 && lastWriteTime != 0 && t != lastWriteTime && !ignore) { try { - collidingId = FileUtils.readFileToString(timestampFile, Charset.defaultCharset()); + collidingId = Files.readString(Util.fileToPath(timestampFile), Charset.defaultCharset()); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Failed to read collision file", e); } @@ -115,7 +116,7 @@ public class DoubleLaunchChecker { } try { - FileUtils.writeStringToFile(timestampFile, getId(), Charset.defaultCharset()); + Files.writeString(Util.fileToPath(timestampFile), getId(), Charset.defaultCharset()); lastWriteTime = timestampFile.lastModified(); } catch (IOException e) { // if failed to write, err on the safe side and assume things are OK. diff --git a/core/src/main/java/jenkins/install/InstallUtil.java b/core/src/main/java/jenkins/install/InstallUtil.java index dcd3ac37de..0572d48a52 100644 --- a/core/src/main/java/jenkins/install/InstallUtil.java +++ b/core/src/main/java/jenkins/install/InstallUtil.java @@ -31,6 +31,7 @@ import com.thoughtworks.xstream.XStream; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Functions; +import hudson.Util; import hudson.model.UpdateCenter.DownloadJob.InstallationStatus; import hudson.model.UpdateCenter.DownloadJob.Installing; import hudson.model.UpdateCenter.InstallationJob; @@ -40,6 +41,7 @@ import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; @@ -53,7 +55,6 @@ import javax.inject.Provider; import jenkins.model.Jenkins; import jenkins.util.SystemProperties; import jenkins.util.xml.XMLUtils; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; @@ -210,7 +211,7 @@ public class InstallUtil { File lastExecVersionFile = getLastExecVersionFile(); if (lastExecVersionFile.exists()) { try { - String version = FileUtils.readFileToString(lastExecVersionFile, Charset.defaultCharset()); + String version = Files.readString(Util.fileToPath(lastExecVersionFile), Charset.defaultCharset()); // JENKINS-37438 blank will force the setup // wizard regardless of current state of the system if (StringUtils.isBlank(version)) { @@ -253,7 +254,7 @@ public class InstallUtil { static void saveLastExecVersion(@NonNull String version) { File lastExecVersionFile = getLastExecVersionFile(); try { - FileUtils.write(lastExecVersionFile, version, Charset.defaultCharset()); + Files.writeString(Util.fileToPath(lastExecVersionFile), version, Charset.defaultCharset()); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to save " + lastExecVersionFile.getAbsolutePath(), e); } @@ -319,7 +320,7 @@ public class InstallUtil { } try { String installingPluginXml = new XStream().toXML(statuses); - FileUtils.write(installingPluginsFile, installingPluginXml); + Files.writeString(Util.fileToPath(installingPluginsFile), installingPluginXml, StandardCharsets.UTF_8); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to save " + installingPluginsFile.getAbsolutePath(), e); } diff --git a/core/src/main/java/jenkins/install/SetupWizard.java b/core/src/main/java/jenkins/install/SetupWizard.java index 6513823cd8..38668be294 100644 --- a/core/src/main/java/jenkins/install/SetupWizard.java +++ b/core/src/main/java/jenkins/install/SetupWizard.java @@ -1,6 +1,5 @@ package jenkins.install; -import static org.apache.commons.io.FileUtils.readFileToString; import static org.apache.commons.lang.StringUtils.defaultIfBlank; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -10,6 +9,7 @@ import hudson.BulkChange; import hudson.Extension; import hudson.FilePath; import hudson.ProxyConfiguration; +import hudson.Util; import hudson.model.DownloadService; import hudson.model.PageDecorator; import hudson.model.UpdateCenter; @@ -32,6 +32,10 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -59,7 +63,6 @@ import jenkins.util.SystemProperties; import jenkins.util.UrlHelper; import net.sf.json.JSONArray; import net.sf.json.JSONObject; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; @@ -229,15 +232,22 @@ public class SetupWizard extends PageDecorator { String plainText; if (sysProp.startsWith("@")) { // no need for path traversal check as it's coming from the instance creator only - File apiTokenFile = new File(sysProp.substring(1)); - if (!apiTokenFile.exists()) { + String apiTokenStr = sysProp.substring(1); + Path apiTokenFile; + try { + apiTokenFile = Paths.get(apiTokenStr); + } catch (InvalidPathException e) { + LOGGER.log(Level.WARNING, "The API Token cannot be retrieved from an invalid path: {0}", apiTokenStr); + return; + } + if (!Files.exists(apiTokenFile)) { LOGGER.log(Level.WARNING, "The API Token cannot be retrieved from a non-existing file: {0}", apiTokenFile); return; } try { - plainText = FileUtils.readFileToString(apiTokenFile, StandardCharsets.UTF_8); - LOGGER.log(Level.INFO, "API Token generated using contents of file: {0}", apiTokenFile.getAbsolutePath()); + plainText = Files.readString(apiTokenFile, StandardCharsets.UTF_8); + LOGGER.log(Level.INFO, "API Token generated using contents of file: {0}", apiTokenFile.toAbsolutePath()); } catch (IOException e) { LOGGER.log(Level.WARNING, String.format("The API Token cannot be retrieved from the file: %s", apiTokenFile), e); return; @@ -450,7 +460,7 @@ public class SetupWizard extends PageDecorator { } /*package*/ void setCurrentLevel(VersionNumber v) throws IOException { - FileUtils.writeStringToFile(getUpdateStateFile(), v.toString(), StandardCharsets.UTF_8); + Files.writeString(Util.fileToPath(getUpdateStateFile()), v.toString(), StandardCharsets.UTF_8); } /** @@ -474,7 +484,7 @@ public class SetupWizard extends PageDecorator { File state = getUpdateStateFile(); if (state.exists()) { try { - from = new VersionNumber(defaultIfBlank(readFileToString(state), "1.0").trim()); + from = new VersionNumber(defaultIfBlank(Files.readString(Util.fileToPath(state), StandardCharsets.UTF_8), "1.0").trim()); } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Cannot read the current version file", ex); return null; diff --git a/core/src/main/java/jenkins/model/RunIdMigrator.java b/core/src/main/java/jenkins/model/RunIdMigrator.java index a2e5b6656e..2a303d3561 100644 --- a/core/src/main/java/jenkins/model/RunIdMigrator.java +++ b/core/src/main/java/jenkins/model/RunIdMigrator.java @@ -62,7 +62,6 @@ import java.util.TreeMap; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang.time.FastDateFormat; import org.apache.tools.ant.BuildException; import org.kohsuke.accmod.Restricted; @@ -109,7 +108,7 @@ public final class RunIdMigrator { } idToNumber = new TreeMap<>(); try { - for (String line : FileUtils.readLines(f)) { + for (String line : Files.readAllLines(Util.fileToPath(f), StandardCharsets.UTF_8)) { int i = line.indexOf(' '); idToNumber.put(line.substring(0, i), Integer.parseInt(line.substring(i + 1))); } @@ -255,7 +254,7 @@ public final class RunIdMigrator { LOGGER.log(WARNING, "found no build.xml in {0}", name); continue; } - String xml = FileUtils.readFileToString(buildXml, StandardCharsets.UTF_8); + String xml = Files.readString(Util.fileToPath(buildXml), StandardCharsets.UTF_8); Matcher m = NUMBER_ELT.matcher(xml); if (!m.find()) { LOGGER.log(WARNING, "could not find in {0}/build.xml", name); @@ -266,7 +265,7 @@ public final class RunIdMigrator { xml = m.replaceFirst(" " + name + "" + nl + " " + timestamp + "" + nl); File newKid = new File(dir, Integer.toString(number)); move(kid, newKid); - FileUtils.writeStringToFile(new File(newKid, "build.xml"), xml, StandardCharsets.UTF_8); + Files.writeString(Util.fileToPath(newKid).resolve("build.xml"), xml, StandardCharsets.UTF_8); LOGGER.log(FINE, "fully processed {0} → {1}", new Object[] {name, number}); idToNumber.put(name, number); } catch (Exception x) { @@ -387,7 +386,7 @@ public final class RunIdMigrator { System.err.println(buildXml + " did not exist"); continue; } - String xml = FileUtils.readFileToString(buildXml, StandardCharsets.UTF_8); + String xml = Files.readString(Util.fileToPath(buildXml), StandardCharsets.UTF_8); Matcher m = TIMESTAMP_ELT.matcher(xml); if (!m.find()) { System.err.println(buildXml + " did not contain as expected"); @@ -405,7 +404,7 @@ public final class RunIdMigrator { // Post-migration build. We give it a new ID based on its timestamp. id = legacyIdFormatter.format(new Date(timestamp)); } - FileUtils.write(buildXml, xml, StandardCharsets.UTF_8); + Files.writeString(Util.fileToPath(buildXml), xml, StandardCharsets.UTF_8); if (!build.renameTo(new File(builds, id))) { System.err.println(build + " could not be renamed"); } diff --git a/core/src/main/java/jenkins/security/stapler/StaplerDispatchValidator.java b/core/src/main/java/jenkins/security/stapler/StaplerDispatchValidator.java index 97b0f782a2..eebfcfdacf 100644 --- a/core/src/main/java/jenkins/security/stapler/StaplerDispatchValidator.java +++ b/core/src/main/java/jenkins/security/stapler/StaplerDispatchValidator.java @@ -189,7 +189,7 @@ public class StaplerDispatchValidator implements DispatchValidator { @VisibleForTesting void loadWhitelist(@NonNull InputStream in) throws IOException { - cache.loadWhitelist(IOUtils.readLines(in)); + cache.loadWhitelist(IOUtils.readLines(in, StandardCharsets.UTF_8)); } private static class ValidatorCache { @@ -280,7 +280,7 @@ public class StaplerDispatchValidator implements DispatchValidator { Path configFile = whitelist != null ? Paths.get(whitelist) : Jenkins.get().getRootDir().toPath().resolve("stapler-views-whitelist.txt"); if (Files.exists(configFile)) { try { - loadWhitelist(Files.readAllLines(configFile)); + loadWhitelist(Files.readAllLines(configFile, StandardCharsets.UTF_8)); } catch (IOException e) { LOGGER.log(Level.WARNING, e, () -> "Could not load user defined whitelist from " + configFile); } diff --git a/core/src/main/java/jenkins/security/stapler/StaticRoutingDecisionProvider.java b/core/src/main/java/jenkins/security/stapler/StaticRoutingDecisionProvider.java index d4edd7aaf2..abc61baf04 100644 --- a/core/src/main/java/jenkins/security/stapler/StaticRoutingDecisionProvider.java +++ b/core/src/main/java/jenkins/security/stapler/StaticRoutingDecisionProvider.java @@ -30,11 +30,13 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.BulkChange; import hudson.Extension; import hudson.ExtensionList; +import hudson.Util; import hudson.model.Saveable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -43,7 +45,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.Jenkins; import jenkins.util.SystemProperties; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; @@ -202,7 +203,7 @@ public class StaticRoutingDecisionProvider extends RoutingDecisionProvider imple .map(signature -> "!" + signature) .forEach(allSignatures::add); - FileUtils.writeLines(file, allSignatures); + Files.write(Util.fileToPath(file), allSignatures, StandardCharsets.UTF_8); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to save " + file.getAbsolutePath(), e); } @@ -235,7 +236,7 @@ public class StaticRoutingDecisionProvider extends RoutingDecisionProvider imple blacklistSignaturesFromUserControlledList = new HashSet<>(); parseFileIntoList( - FileUtils.readLines(file, StandardCharsets.UTF_8), + Files.readAllLines(Util.fileToPath(file), StandardCharsets.UTF_8), whitelistSignaturesFromUserControlledList, blacklistSignaturesFromUserControlledList ); diff --git a/core/src/test/java/hudson/LauncherTest.java b/core/src/test/java/hudson/LauncherTest.java index 69add4199a..b7ea305afd 100644 --- a/core/src/test/java/hudson/LauncherTest.java +++ b/core/src/test/java/hudson/LauncherTest.java @@ -38,8 +38,8 @@ import hudson.util.StreamTaskListener; import java.io.ByteArrayOutputStream; import java.io.File; import java.nio.charset.Charset; +import java.nio.file.Files; import jenkins.security.MasterToSlaveCallable; -import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -69,7 +69,7 @@ public class LauncherTest { assertTrue("Join did not finish promptly. The completion time (" + terminationTime + "ms) is longer than expected 15s", terminationTime < 15000); channels.french.call(new NoopCallable()); // this only returns after the other side of the channel has finished executing cancellation Thread.sleep(2000); // more delay to make sure it's gone - assertNull("process should be gone", ProcessTree.get().get(Integer.parseInt(FileUtils.readFileToString(tmp, Charset.defaultCharset()).trim()))); + assertNull("process should be gone", ProcessTree.get().get(Integer.parseInt(Files.readString(tmp.toPath(), Charset.defaultCharset()).trim()))); // Manual version of test: set up instance w/ one agent. Now in script console // new hudson.FilePath(new java.io.File("/tmp")).createLauncher(new hudson.util.StreamTaskListener(System.err)). diff --git a/core/src/test/java/hudson/PluginManagerTest.java b/core/src/test/java/hudson/PluginManagerTest.java index c1c471d07f..87e074477c 100644 --- a/core/src/test/java/hudson/PluginManagerTest.java +++ b/core/src/test/java/hudson/PluginManagerTest.java @@ -44,7 +44,6 @@ import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; @@ -149,13 +148,13 @@ public class PluginManagerTest { "Plugin-Developers: "; private File createHpiWithManifest() throws IOException { - String manifestPath = "META-INF/MANIFEST.MF"; - new File("META-INF").mkdir(); - FileUtils.write(new File(tmp.toFile(), manifestPath), SAMPLE_MANIFEST_FILE, StandardCharsets.UTF_8); + Path metaInf = tmp.resolve("META-INF"); + Files.createDirectory(metaInf); + Files.writeString(metaInf.resolve("MANIFEST.MF"), SAMPLE_MANIFEST_FILE, StandardCharsets.UTF_8); final File f = new File(tmp.toFile(), "my.hpi"); try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(f.toPath()))) { - ZipEntry e = new ZipEntry(manifestPath); + ZipEntry e = new ZipEntry("META-INF/MANIFEST.MF"); out.putNextEntry(e); byte[] data = SAMPLE_MANIFEST_FILE.getBytes(StandardCharsets.UTF_8); out.write(data, 0, data.length); diff --git a/core/src/test/java/hudson/UtilTest.java b/core/src/test/java/hudson/UtilTest.java index 0ee6eb2a56..088591e5dd 100644 --- a/core/src/test/java/hudson/UtilTest.java +++ b/core/src/test/java/hudson/UtilTest.java @@ -58,7 +58,6 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; -import org.apache.commons.io.FileUtils; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Assert; @@ -612,7 +611,7 @@ public class UtilTest { File aa = new File(a, "aa"); aa.mkdirs(); File aaTxt = new File(aa, "aa.txt"); - FileUtils.write(aaTxt, "aa", StandardCharsets.US_ASCII, false); + Files.writeString(aaTxt.toPath(), "aa", StandardCharsets.US_ASCII); File b = new File(root, "b"); b.mkdir(); diff --git a/core/src/test/java/hudson/util/AtomicFileWriterTest.java b/core/src/test/java/hudson/util/AtomicFileWriterTest.java index a999019d23..00a0a8374e 100644 --- a/core/src/test/java/hudson/util/AtomicFileWriterTest.java +++ b/core/src/test/java/hudson/util/AtomicFileWriterTest.java @@ -22,7 +22,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; -import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -69,7 +68,7 @@ public class AtomicFileWriterTest { @Before public void setUp() throws IOException { af = tmp.newFile(); - FileUtils.writeStringToFile(af, PREVIOUS, Charset.defaultCharset()); + Files.writeString(af.toPath(), PREVIOUS, Charset.defaultCharset()); afw = new AtomicFileWriter(af.toPath(), Charset.defaultCharset()); } @@ -119,7 +118,7 @@ public class AtomicFileWriterTest { // Then assertEquals(expectedContent.length() + 3, Files.size(af.toPath())); - assertEquals(expectedContent + "hey", FileUtils.readFileToString(af, Charset.defaultCharset())); + assertEquals(expectedContent + "hey", Files.readString(af.toPath(), Charset.defaultCharset())); } @Test @@ -132,14 +131,14 @@ public class AtomicFileWriterTest { // Then assertTrue(Files.notExists(afw.getTemporaryPath())); - assertEquals(PREVIOUS, FileUtils.readFileToString(af, Charset.defaultCharset())); + assertEquals(PREVIOUS, Files.readString(af.toPath(), Charset.defaultCharset())); } @Test public void indexOutOfBoundsLeavesOriginalUntouched() throws Exception { // Given assertThrows(IndexOutOfBoundsException.class, () -> afw.write(expectedContent, 0, expectedContent.length() + 10)); - assertEquals(PREVIOUS, FileUtils.readFileToString(af, Charset.defaultCharset())); + assertEquals(PREVIOUS, Files.readString(af.toPath(), Charset.defaultCharset())); } @Test diff --git a/core/src/test/java/hudson/util/FileChannelWriterTest.java b/core/src/test/java/hudson/util/FileChannelWriterTest.java index 13f8b89b70..fd190c24ee 100644 --- a/core/src/test/java/hudson/util/FileChannelWriterTest.java +++ b/core/src/test/java/hudson/util/FileChannelWriterTest.java @@ -8,8 +8,8 @@ import java.io.File; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.StandardOpenOption; -import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -55,6 +55,6 @@ public class FileChannelWriterTest { private void assertContent(String string) throws IOException { - assertThat(FileUtils.readFileToString(file, StandardCharsets.UTF_8), equalTo(string)); + assertThat(Files.readString(file.toPath(), StandardCharsets.UTF_8), equalTo(string)); } } diff --git a/core/src/test/java/hudson/util/SecretRewriterTest.java b/core/src/test/java/hudson/util/SecretRewriterTest.java index 6cd12245da..ff13cd9152 100644 --- a/core/src/test/java/hudson/util/SecretRewriterTest.java +++ b/core/src/test/java/hudson/util/SecretRewriterTest.java @@ -10,13 +10,13 @@ import hudson.model.TaskListener; import java.io.File; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.util.Arrays; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Base64; import java.util.List; import java.util.regex.Pattern; import javax.crypto.Cipher; import jenkins.security.ConfidentialStoreRule; -import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -50,11 +50,11 @@ public class SecretRewriterTest { private String roundtrip(String before) throws Exception { SecretRewriter sr = new SecretRewriter(); - File f = File.createTempFile("test", "xml", tmp.getRoot()); - FileUtils.write(f, before, Charset.defaultCharset()); - sr.rewrite(f); + Path path = Files.createTempFile(tmp.getRoot().toPath(), "test", "xml"); + Files.writeString(path, before, Charset.defaultCharset()); + sr.rewrite(path.toFile()); //assert after.replaceAll(System.getProperty("line.separator"), "\n").trim()==f.text.replaceAll(System.getProperty("line.separator"), "\n").trim() - return FileUtils.readFileToString(f, Charset.defaultCharset()).replaceAll(System.getProperty("line.separator"), "\n").trim(); + return Files.readString(path, Charset.defaultCharset()).replaceAll(System.getProperty("line.separator"), "\n").trim(); } @SuppressWarnings("deprecation") @@ -83,16 +83,16 @@ public class SecretRewriterTest { // set up some directories with stuff File t = tmp.newFolder("t"); - List dirs = Arrays.asList("a", "b", "c", "c/d", "c/d/e"); + List dirs = List.of("a", "b", "c", "c/d", "c/d/e"); for (String p : dirs) { File d = new File(t, p); d.mkdir(); - FileUtils.write(new File(d, "foo.xml"), payload, Charset.defaultCharset()); + Files.writeString(d.toPath().resolve("foo.xml"), payload, Charset.defaultCharset()); } // stuff outside File t2 = tmp.newFolder("t2"); - FileUtils.write(new File(t2, "foo.xml"), payload, Charset.defaultCharset()); + Files.writeString(t2.toPath().resolve("foo.xml"), payload, Charset.defaultCharset()); // some recursions as well as valid symlinks new FilePath(t).child("c/symlink").symlinkTo("..", st); @@ -102,11 +102,11 @@ public class SecretRewriterTest { assertEquals(6, sw.rewriteRecursive(t, st)); for (String p : dirs) { - assertTrue(MSG_PATTERN.matcher(FileUtils.readFileToString(new File(t, p + "/foo.xml"), Charset.defaultCharset()).trim()).matches()); + assertTrue(MSG_PATTERN.matcher(Files.readString(new File(t, p + "/foo.xml").toPath(), Charset.defaultCharset()).trim()).matches()); } // t2 is only reachable by following a symlink. this should be covered, too - assertTrue(MSG_PATTERN.matcher(FileUtils.readFileToString(new File(t2, "foo.xml"), Charset.defaultCharset()).trim()).matches()); + assertTrue(MSG_PATTERN.matcher(Files.readString(new File(t2, "foo.xml").toPath(), Charset.defaultCharset()).trim()).matches()); } } diff --git a/core/src/test/java/hudson/util/TextFileTest.java b/core/src/test/java/hudson/util/TextFileTest.java index a8cf7ecc69..0f4315fabe 100644 --- a/core/src/test/java/hudson/util/TextFileTest.java +++ b/core/src/test/java/hudson/util/TextFileTest.java @@ -6,6 +6,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.nio.charset.Charset; +import java.nio.file.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.junit.Rule; @@ -31,7 +32,7 @@ public class TextFileTest { @Test public void shortHead() throws Exception { File f = tmp.newFile(); - FileUtils.write(f, "hello", Charset.defaultCharset()); + Files.writeString(f.toPath(), "hello", Charset.defaultCharset()); TextFile t = new TextFile(f); assertEquals("hello", t.head(35)); @@ -41,7 +42,7 @@ public class TextFileTest { public void tail() throws Exception { File f = tmp.newFile(); FileUtils.copyURLToFile(getClass().getResource("ascii.txt"), f); - String whole = FileUtils.readFileToString(f, Charset.defaultCharset()); + String whole = Files.readString(f.toPath(), Charset.defaultCharset()); TextFile t = new TextFile(f); String tailStr = whole.substring(whole.length() - 34); assertEquals(tailStr, t.fastTail(tailStr.length())); @@ -50,7 +51,7 @@ public class TextFileTest { @Test public void shortTail() throws Exception { File f = tmp.newFile(); - FileUtils.write(f, "hello", Charset.defaultCharset()); + Files.writeString(f.toPath(), "hello", Charset.defaultCharset()); TextFile t = new TextFile(f); assertEquals("hello", t.fastTail(35)); diff --git a/core/src/test/java/jenkins/model/RunIdMigratorTest.java b/core/src/test/java/jenkins/model/RunIdMigratorTest.java index 33588278a4..9a74d27607 100644 --- a/core/src/test/java/jenkins/model/RunIdMigratorTest.java +++ b/core/src/test/java/jenkins/model/RunIdMigratorTest.java @@ -36,6 +36,8 @@ import hudson.util.StreamTaskListener; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; @@ -309,7 +311,9 @@ public class RunIdMigratorTest { // TODO test sane recovery from various error conditions private void write(String file, String text) throws Exception { - FileUtils.write(new File(dir, file), text, Charset.defaultCharset()); + Path path = new File(dir, file).toPath(); + Files.createDirectories(path.getParent()); + Files.writeString(path, text, Charset.defaultCharset()); } private void link(String symlink, String dest) throws Exception { @@ -329,7 +333,7 @@ public class RunIdMigratorTest { if (symlink != null) { notation = "→" + symlink; } else if (kid.isFile()) { - notation = "'" + FileUtils.readFileToString(kid, Charset.defaultCharset()) + "'"; + notation = "'" + Files.readString(kid.toPath(), Charset.defaultCharset()) + "'"; } else if (kid.isDirectory()) { notation = summarize(kid); } else { diff --git a/core/src/test/java/jenkins/model/lazy/FakeMap.java b/core/src/test/java/jenkins/model/lazy/FakeMap.java index 70b1c87f3e..ae2198e391 100644 --- a/core/src/test/java/jenkins/model/lazy/FakeMap.java +++ b/core/src/test/java/jenkins/model/lazy/FakeMap.java @@ -27,7 +27,7 @@ package jenkins.model.lazy; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; -import org.apache.commons.io.FileUtils; +import java.nio.file.Files; /** * @author Kohsuke Kawaguchi @@ -44,7 +44,7 @@ public class FakeMap extends AbstractLazyLoadRunMap { @Override protected Build retrieve(File dir) throws IOException { - String n = FileUtils.readFileToString(new File(dir, "n"), Charset.defaultCharset()).trim(); + String n = Files.readString(dir.toPath().resolve("n"), Charset.defaultCharset()).trim(); //new Exception("loading #" + n).printStackTrace(); return new Build(Integer.parseInt(n)); } diff --git a/core/src/test/java/jenkins/model/lazy/FakeMapBuilder.java b/core/src/test/java/jenkins/model/lazy/FakeMapBuilder.java index 59f86a4f45..8bb47106bb 100644 --- a/core/src/test/java/jenkins/model/lazy/FakeMapBuilder.java +++ b/core/src/test/java/jenkins/model/lazy/FakeMapBuilder.java @@ -27,6 +27,7 @@ package jenkins.model.lazy; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import org.apache.commons.io.FileUtils; import org.junit.rules.TestRule; import org.junit.runner.Description; @@ -49,8 +50,8 @@ public class FakeMapBuilder implements TestRule { public FakeMapBuilder add(int n) throws IOException { File build = new File(dir, Integer.toString(n)); - FileUtils.writeStringToFile(new File(build, "n"), Integer.toString(n), StandardCharsets.US_ASCII); - build.mkdir(); + Files.createDirectory(build.toPath()); + Files.writeString(build.toPath().resolve("n"), Integer.toString(n), StandardCharsets.US_ASCII); return this; } diff --git a/core/src/test/java/jenkins/security/DefaultConfidentialStoreTest.java b/core/src/test/java/jenkins/security/DefaultConfidentialStoreTest.java index 2475d7714b..117e1d5b18 100644 --- a/core/src/test/java/jenkins/security/DefaultConfidentialStoreTest.java +++ b/core/src/test/java/jenkins/security/DefaultConfidentialStoreTest.java @@ -1,17 +1,16 @@ package jenkins.security; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import hudson.FilePath; import hudson.Functions; import java.io.File; +import java.nio.charset.MalformedInputException; import java.nio.charset.StandardCharsets; -import org.apache.commons.io.FileUtils; +import java.nio.file.Files; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -37,7 +36,7 @@ public class DefaultConfidentialStoreTest { assertTrue(new File(tmp, "test").exists()); assertTrue(new File(tmp, "master.key").exists()); - assertThat(FileUtils.readFileToString(new File(tmp, "test"), StandardCharsets.UTF_8), not(containsString("Hello"))); // the data shouldn't be a plain text, obviously + assertThrows(MalformedInputException.class, () -> Files.readString(tmp.toPath().resolve("test"), StandardCharsets.UTF_8)); // the data shouldn't be a plain text, obviously if (!Functions.isWindows()) { assertEquals(0700, new FilePath(tmp).mode() & 0777); // should be read only diff --git a/core/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java b/core/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java index d4af5a1bd9..fc3fd57d01 100644 --- a/core/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java +++ b/core/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java @@ -41,6 +41,7 @@ import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.nio.charset.Charset; +import java.nio.file.Files; import java.text.SimpleDateFormat; import java.time.temporal.ChronoUnit; import java.util.Arrays; @@ -51,7 +52,6 @@ import java.util.List; import java.util.Random; import java.util.UUID; import java.util.stream.Collectors; -import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -203,10 +203,10 @@ public class ApiTokenStatsTest { { // replace the ID_1 with ID_2 in the file XmlFile statsFile = ApiTokenStats.getConfigFile(tmp.getRoot()); - String content = FileUtils.readFileToString(statsFile.getFile(), Charset.defaultCharset()); + String content = Files.readString(statsFile.getFile().toPath(), Charset.defaultCharset()); // now there are multiple times the same id in the file with different stats String newContentWithDuplicatedId = content.replace(ID_1, ID_2).replace(ID_3, ID_2); - FileUtils.write(statsFile.getFile(), newContentWithDuplicatedId, Charset.defaultCharset()); + Files.writeString(statsFile.getFile().toPath(), newContentWithDuplicatedId, Charset.defaultCharset()); } { diff --git a/core/src/test/java/jenkins/util/VirtualFileTest.java b/core/src/test/java/jenkins/util/VirtualFileTest.java index 048487d499..e77a9268c7 100644 --- a/core/src/test/java/jenkins/util/VirtualFileTest.java +++ b/core/src/test/java/jenkins/util/VirtualFileTest.java @@ -86,10 +86,10 @@ public class VirtualFileTest { @Test public void outsideSymlinks() throws Exception { assumeFalse(Functions.isWindows()); File ws = tmp.newFolder("ws"); - FileUtils.write(new File(ws, "safe"), "safe", StandardCharsets.US_ASCII, false); + Files.writeString(ws.toPath().resolve("safe"), "safe", StandardCharsets.US_ASCII); Util.createSymlink(ws, "safe", "supported", TaskListener.NULL); File other = tmp.newFolder("other"); - FileUtils.write(new File(other, "secret"), "s3cr3t", StandardCharsets.US_ASCII, false); + Files.writeString(other.toPath().resolve("secret"), "s3cr3t", StandardCharsets.US_ASCII); Util.createSymlink(ws, "../other/secret", "hack", TaskListener.NULL); VirtualFile root = VirtualFile.forFile(ws); VirtualFile supported = root.child("supported"); @@ -759,19 +759,19 @@ public class VirtualFileTest { File aaa = new File(aa, "aaa"); aaa.mkdirs(); File aaTxt = new File(aa, "aa.txt"); - FileUtils.write(aaTxt, "aa", StandardCharsets.US_ASCII, false); + Files.writeString(aaTxt.toPath(), "aa", StandardCharsets.US_ASCII); File ab = new File(a, "ab"); ab.mkdirs(); File abTxt = new File(ab, "ab.txt"); - FileUtils.write(abTxt, "ab", StandardCharsets.US_ASCII, false); + Files.writeString(abTxt.toPath(), "ab", StandardCharsets.US_ASCII); File b = new File(root, "b"); File ba = new File(b, "ba"); ba.mkdirs(); File baTxt = new File(ba, "ba.txt"); - FileUtils.write(baTxt, "ba", StandardCharsets.US_ASCII, false); + Files.writeString(baTxt.toPath(), "ba", StandardCharsets.US_ASCII); File _a = new File(b, "_a"); new FilePath(_a).symlinkTo(a.getAbsolutePath(), TaskListener.NULL); @@ -1041,7 +1041,7 @@ public class VirtualFileTest { public void testLength_FileVF() throws IOException { File ws = tmp.newFolder("ws"); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); VirtualFile child = VirtualFile.forFile(ws).child(childString); assertThat(child.length(), is((long) childString.length())); } @@ -1120,7 +1120,7 @@ public class VirtualFileTest { // which generally does nothing. File ws = tmp.newFolder("ws"); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); VirtualFile child = new VirtualFileMinimalImplementation(ws).child(childString); String fileContents = IOUtils.toString(child.open()); assertThat(childString, is(fileContents)); @@ -1134,7 +1134,7 @@ public class VirtualFileTest { // which generally does nothing. File ws = tmp.newFolder("ws"); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); String linkString = "link"; Util.createSymlink(ws, childString, linkString, TaskListener.NULL); @@ -1148,7 +1148,7 @@ public class VirtualFileTest { public void testOpenNoFollowLinks_NoFollowsLink_FileVF() throws Exception { File ws = tmp.newFolder("ws"); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); String linkString = "link"; Util.createSymlink(ws, childString, linkString, TaskListener.NULL); @@ -1164,7 +1164,7 @@ public class VirtualFileTest { String symlinkName = "symlink"; Util.createSymlink(tmp.getRoot(), ws.getName(), symlinkName, null); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); File childThroughSymlink = new File(tmp.getRoot(), "/" + symlinkName + "/" + childString); VirtualFile child = rootVirtualFile.child(symlinkName).child(childString); assertThrows("Should have not followed links", IOException.class, () -> child.open(true)); @@ -1177,7 +1177,7 @@ public class VirtualFileTest { String symlinkName = "symlink"; Util.createSymlink(tmp.getRoot(), ws.getName(), symlinkName, null); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); VirtualFile rootVirtualPath = VirtualFile.forFilePath(new FilePath(tmp.getRoot())); VirtualFile childVirtualPath = rootVirtualPath.child(symlinkName).child(childString); assertThrows("Should have not followed links", IOException.class, () -> childVirtualPath.open(true)); @@ -1188,7 +1188,7 @@ public class VirtualFileTest { public void testOpenNoFollowLinks_NoFollowsLink_FilePathVF() throws Exception { File ws = tmp.newFolder("ws"); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); String linkString = "link"; Util.createSymlink(ws, childString, linkString, TaskListener.NULL); @@ -1236,7 +1236,7 @@ public class VirtualFileTest { public void testLength_FilePathVF() throws IOException { File ws = tmp.newFolder("ws"); String childString = "child"; - FileUtils.write(new File(ws, childString), childString); + Files.writeString(ws.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); VirtualFile child = VirtualFile.forFilePath(new FilePath(ws)).child(childString); assertThat(child.length(), is((long) childString.length())); } @@ -1493,7 +1493,7 @@ public class VirtualFileTest { String externalFolderName = "external"; File externalFile = tmp.newFolder(externalFolderName); String childString = "child"; - FileUtils.write(new File(externalFile, childString), childString); + Files.writeString(externalFile.toPath().resolve(childString), childString, StandardCharsets.US_ASCII); Util.createSymlink(ws, "../" + externalFolderName, "invalidSymlink", TaskListener.NULL); return ws; } diff --git a/test/src/test/java/hudson/LauncherTest.java b/test/src/test/java/hudson/LauncherTest.java index 730e9acfa2..bcb6b4f551 100644 --- a/test/src/test/java/hudson/LauncherTest.java +++ b/test/src/test/java/hudson/LauncherTest.java @@ -58,9 +58,9 @@ import java.io.OutputStream; import java.io.PrintStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -198,7 +198,7 @@ public class LauncherTest { ps.cmds("echo", "hello"); } assertEquals(0, ps.stdout(listener).join()); - assertThat(FileUtils.readFileToString(log, StandardCharsets.UTF_8).replace("\r\n", "\n"), + assertThat(Files.readString(log.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n"), containsString("[master → slave0] $ " + (Functions.isWindows() ? "cmd /c " : "") + "echo hello\n" + "[master → slave0] hello")); } diff --git a/test/src/test/java/hudson/model/AbstractItemTest.java b/test/src/test/java/hudson/model/AbstractItemTest.java index 1f6c709027..7c240eb961 100644 --- a/test/src/test/java/hudson/model/AbstractItemTest.java +++ b/test/src/test/java/hudson/model/AbstractItemTest.java @@ -14,14 +14,14 @@ import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.AccessDeniedException3; import hudson.util.FormValidation; -import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import jenkins.model.Jenkins; import jenkins.model.ProjectNamingStrategy; -import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; @@ -47,8 +47,8 @@ public class AbstractItemTest { b.setDescription("This is my build"); // update on disk representation - File f = p.getConfigFile().getFile(); - FileUtils.writeStringToFile(f, FileUtils.readFileToString(f, StandardCharsets.UTF_8).replaceAll("Hello World", "Good Evening"), StandardCharsets.UTF_8); + Path path = p.getConfigFile().getFile().toPath(); + Files.writeString(path, Files.readString(path, StandardCharsets.UTF_8).replaceAll("Hello World", "Good Evening"), StandardCharsets.UTF_8); // reload away p.doReload(); diff --git a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java index 2c3d548009..41c2e0672b 100644 --- a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java +++ b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java @@ -67,6 +67,8 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -82,7 +84,6 @@ import jenkins.model.ArtifactManagerFactory; import jenkins.model.ArtifactManagerFactoryDescriptor; import jenkins.model.Jenkins; import jenkins.util.VirtualFile; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; @@ -579,7 +580,7 @@ public class DirectoryBrowserSupportTest { File secretsFolder = new File(j.jenkins.getRootDir(), "secrets"); File secretTarget = new File(secretsFolder, "goal.txt"); String secretContent = "secret"; - FileUtils.write(secretTarget, secretContent, StandardCharsets.UTF_8); + Files.writeString(secretTarget.toPath(), secretContent, StandardCharsets.UTF_8); /* * secrets/ @@ -718,10 +719,10 @@ public class DirectoryBrowserSupportTest { File secretsFolder = new File(j.jenkins.getRootDir(), "secrets"); File secretTarget = new File(secretsFolder, "goal.txt"); String secretContent = "secret"; - FileUtils.write(secretTarget, secretContent, StandardCharsets.UTF_8); - FileUtils.write(new File(secretsFolder, "public_fake1.key"), secretContent, StandardCharsets.UTF_8); - FileUtils.write(new File(secretsFolder, "public_fake2.key"), secretContent, StandardCharsets.UTF_8); - FileUtils.write(new File(secretsFolder, "public_fake3.key"), secretContent, StandardCharsets.UTF_8); + Files.writeString(secretTarget.toPath(), secretContent, StandardCharsets.UTF_8); + Files.writeString(secretsFolder.toPath().resolve("public_fake1.key"), secretContent, StandardCharsets.UTF_8); + Files.writeString(secretsFolder.toPath().resolve("public_fake2.key"), secretContent, StandardCharsets.UTF_8); + Files.writeString(secretsFolder.toPath().resolve("public_fake3.key"), secretContent, StandardCharsets.UTF_8); /* * secrets/ @@ -792,7 +793,7 @@ public class DirectoryBrowserSupportTest { File secretsFolder = new File(j.jenkins.getRootDir(), "secrets"); File secretTarget = new File(secretsFolder, "goal.txt"); String secretContent = "secret"; - FileUtils.write(secretTarget, secretContent, StandardCharsets.UTF_8); + Files.writeString(secretTarget.toPath(), secretContent, StandardCharsets.UTF_8); /* * secrets/ @@ -1013,7 +1014,7 @@ public class DirectoryBrowserSupportTest { folderInsideWorkspace.mkdir(); File fileTarget = new File(folderInsideWorkspace, "goal.txt"); String publicContent = "not-secret"; - FileUtils.write(fileTarget, publicContent, StandardCharsets.UTF_8); + Files.writeString(fileTarget.toPath(), publicContent, StandardCharsets.UTF_8); /* * workspace/ @@ -1091,8 +1092,8 @@ public class DirectoryBrowserSupportTest { if (resourceUrl == null) { fail("The resource with fileName " + fileNameInResources + " is not present in the resources of the test"); } - File resourceFile = new File(resourceUrl.toURI()); - return FileUtils.readFileToString(resourceFile, StandardCharsets.UTF_8); + Path resourcePath = Paths.get(resourceUrl.toURI()); + return Files.readString(resourcePath, StandardCharsets.UTF_8); } @Test @@ -1100,12 +1101,12 @@ public class DirectoryBrowserSupportTest { public void windows_cannotViewAbsolutePath() throws Exception { Assume.assumeTrue("can only be tested this on Windows", Functions.isWindows()); - File targetTmpFile = File.createTempFile("sec2481", "tmp"); + Path targetTmpPath = Files.createTempFile("sec2481", "tmp"); String content = "random data provided as fixed value"; - FileUtils.writeStringToFile(targetTmpFile, content, StandardCharsets.UTF_8); + Files.writeString(targetTmpPath, content, StandardCharsets.UTF_8); JenkinsRule.WebClient wc = j.createWebClient().withThrowExceptionOnFailingStatusCode(false); - Page page = wc.goTo("userContent/" + targetTmpFile.getAbsolutePath() + "/*view*", null); + Page page = wc.goTo("userContent/" + targetTmpPath.toAbsolutePath() + "/*view*", null); MatcherAssert.assertThat(page.getWebResponse().getStatusCode(), CoreMatchers.equalTo(404)); } @@ -1118,12 +1119,12 @@ public class DirectoryBrowserSupportTest { String originalValue = System.getProperty(DirectoryBrowserSupport.ALLOW_ABSOLUTE_PATH_PROPERTY_NAME); System.setProperty(DirectoryBrowserSupport.ALLOW_ABSOLUTE_PATH_PROPERTY_NAME, "true"); try { - File targetTmpFile = File.createTempFile("sec2481", "tmp"); + Path targetTmpPath = Files.createTempFile("sec2481", "tmp"); String content = "random data provided as fixed value"; - FileUtils.writeStringToFile(targetTmpFile, content, StandardCharsets.UTF_8); + Files.writeString(targetTmpPath, content, StandardCharsets.UTF_8); JenkinsRule.WebClient wc = j.createWebClient().withThrowExceptionOnFailingStatusCode(false); - Page page = wc.goTo("userContent/" + targetTmpFile.getAbsolutePath() + "/*view*", null); + Page page = wc.goTo("userContent/" + targetTmpPath.toAbsolutePath() + "/*view*", null); MatcherAssert.assertThat(page.getWebResponse().getStatusCode(), CoreMatchers.equalTo(200)); MatcherAssert.assertThat(page.getWebResponse().getContentAsString(), CoreMatchers.containsString(content)); @@ -1142,7 +1143,7 @@ public class DirectoryBrowserSupportTest { File testFile = new File(j.jenkins.getRootDir(), "userContent/test.txt"); String content = "random data provided as fixed value"; - FileUtils.writeStringToFile(testFile, content, StandardCharsets.UTF_8); + Files.writeString(testFile.toPath(), content, StandardCharsets.UTF_8); JenkinsRule.WebClient wc = j.createWebClient().withThrowExceptionOnFailingStatusCode(false); Page page = wc.goTo("userContent/test.txt/*view*", null); diff --git a/test/src/test/java/hudson/model/FileParameterValueTest.java b/test/src/test/java/hudson/model/FileParameterValueTest.java index 84e71a9a3d..06eca9589a 100644 --- a/test/src/test/java/hudson/model/FileParameterValueTest.java +++ b/test/src/test/java/hudson/model/FileParameterValueTest.java @@ -40,10 +40,10 @@ import hudson.FilePath; import hudson.Functions; import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.apache.commons.io.FileUtils; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; @@ -75,7 +75,7 @@ public class FileParameterValueTest { String uploadedContent = "test-content"; File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, uploadedContent, StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), uploadedContent, StandardCharsets.UTF_8); FreeStyleBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("../../../../../root-level.txt", uploadedFile, "uploaded-file.txt") @@ -115,7 +115,7 @@ public class FileParameterValueTest { String uploadedContent = "test-content"; File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, uploadedContent, StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), uploadedContent, StandardCharsets.UTF_8); FreeStyleBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("dir/../../../pwned", uploadedFile, "uploaded-file.txt") @@ -142,7 +142,7 @@ public class FileParameterValueTest { String uploadedContent = "test-content"; File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, uploadedContent, StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), uploadedContent, StandardCharsets.UTF_8); FreeStyleBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("../pwned", uploadedFile, "uploaded-file.txt") @@ -180,7 +180,7 @@ public class FileParameterValueTest { String uploadedContent = "test-content"; File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, uploadedContent, StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), uploadedContent, StandardCharsets.UTF_8); FreeStyleBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("..\\..\\..\\..\\..\\root-level.txt", uploadedFile, "uploaded-file.txt") @@ -209,7 +209,7 @@ public class FileParameterValueTest { String uploadedContent = "test-content"; File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, uploadedContent, StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), uploadedContent, StandardCharsets.UTF_8); FreeStyleBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue(".", uploadedFile, "uploaded-file.txt") @@ -237,7 +237,7 @@ public class FileParameterValueTest { String uploadedContent = "test-content"; File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, uploadedContent, StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), uploadedContent, StandardCharsets.UTF_8); FreeStyleBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("..", uploadedFile, "uploaded-file.txt") @@ -271,7 +271,7 @@ public class FileParameterValueTest { String uploadedContent = "test-content"; File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, uploadedContent, StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), uploadedContent, StandardCharsets.UTF_8); FreeStyleBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("../../../../../root-level.txt", uploadedFile, "uploaded-file.txt") @@ -296,9 +296,9 @@ public class FileParameterValueTest { ))); File uploadedFile1 = tmp.newFile(); - FileUtils.write(uploadedFile1, "test1", StandardCharsets.UTF_8); + Files.writeString(uploadedFile1.toPath(), "test1", StandardCharsets.UTF_8); File uploadedFile2 = tmp.newFile(); - FileUtils.write(uploadedFile2, "test2", StandardCharsets.UTF_8); + Files.writeString(uploadedFile2.toPath(), "test2", StandardCharsets.UTF_8); FreeStyleBuild build = j.assertBuildStatusSuccess(p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("direct-child1.txt", uploadedFile1, "uploaded-file-1.txt"), @@ -337,7 +337,7 @@ public class FileParameterValueTest { ))); File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, "test1", StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), "test1", StandardCharsets.UTF_8); FreeStyleBuild build = j.assertBuildStatusSuccess(p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("weird..name.txt", uploadedFile, "uploaded-file.txt") @@ -365,7 +365,7 @@ public class FileParameterValueTest { ))); File uploadedFile = tmp.newFile(); - FileUtils.write(uploadedFile, "test1", StandardCharsets.UTF_8); + Files.writeString(uploadedFile.toPath(), "test1", StandardCharsets.UTF_8); FreeStyleBuild build = j.assertBuildStatusSuccess(p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new FileParameterValue("~name", uploadedFile, "uploaded-file.txt") diff --git a/test/src/test/java/hudson/model/FingerprintTest.java b/test/src/test/java/hudson/model/FingerprintTest.java index cbc6ee91af..d4f92ffa2d 100644 --- a/test/src/test/java/hudson/model/FingerprintTest.java +++ b/test/src/test/java/hudson/model/FingerprintTest.java @@ -56,6 +56,7 @@ import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; @@ -67,7 +68,6 @@ import java.util.logging.Level; import jenkins.fingerprints.FileFingerprintStorage; import jenkins.model.FingerprintFacet; import jenkins.model.Jenkins; -import org.apache.commons.io.FileUtils; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; @@ -120,7 +120,6 @@ public class FingerprintTest { f.facets.setOwner(Saveable.NOOP); f.facets.add(new TestFacet(f, 123, "val")); f.save(); - //System.out.println(FileUtils.readFileToString(xml)); f2 = Fingerprint.load(SOME_MD5); assertEquals(f.toString(), f2.toString()); assertEquals(1, f2.facets.size()); @@ -573,7 +572,7 @@ public class FingerprintTest { Fingerprint fp = getFingerprint(build, "test.txt"); File targetFile = new File(rule.jenkins.getRootDir(), "../cf7.xml"); - FileUtils.writeStringToFile(targetFile, TEST_FINGERPRINT_CONFIG_FILE_CONTENT, StandardCharsets.UTF_8); + Files.writeString(targetFile.toPath(), TEST_FINGERPRINT_CONFIG_FILE_CONTENT, StandardCharsets.UTF_8); targetFile.deleteOnExit(); String first = fp.getHashString().substring(0, 2); diff --git a/test/src/test/java/hudson/model/FreestyleJobPublisherTest.java b/test/src/test/java/hudson/model/FreestyleJobPublisherTest.java index 24bfe3fcd0..947277ac43 100644 --- a/test/src/test/java/hudson/model/FreestyleJobPublisherTest.java +++ b/test/src/test/java/hudson/model/FreestyleJobPublisherTest.java @@ -8,9 +8,9 @@ import hudson.model.utils.IOExceptionPublisher; import hudson.model.utils.ResultWriterPublisher; import hudson.model.utils.TrueFalsePublisher; import hudson.tasks.ArtifactArchiver; -import java.io.File; import java.nio.charset.StandardCharsets; -import org.apache.commons.io.FileUtils; +import java.nio.file.Files; +import java.nio.file.Path; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -41,9 +41,9 @@ public class FreestyleJobPublisherTest { p.getPublishersList().add(artifactArchiver); // transfer file to build dir FreeStyleBuild b = j.buildAndAssertStatus(Result.FAILURE, p); - File file = new File(b.getArtifactsDir(), "result.txt"); - assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists()); - assertEquals("Publisher, after publisher with return false status, must see FAILURE status", FileUtils.readFileToString(file, StandardCharsets.UTF_8), Result.FAILURE.toString()); + Path path = b.getArtifactsDir().toPath().resolve("result.txt"); + assertTrue("ArtifactArchiver is executed even prior publisher fails", Files.exists(path)); + assertEquals("Publisher, after publisher with return false status, must see FAILURE status", Files.readString(path, StandardCharsets.UTF_8), Result.FAILURE.toString()); } /** @@ -65,9 +65,9 @@ public class FreestyleJobPublisherTest { j.assertLogNotContains("\tat", b); // log must not contain stacktrace j.assertLogContains("Threw AbortException from publisher!", b); // log must contain exact error message - File file = new File(b.getArtifactsDir(), "result.txt"); - assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists()); - assertEquals("Third publisher must see FAILURE status", FileUtils.readFileToString(file, StandardCharsets.UTF_8), Result.FAILURE.toString()); + Path path = b.getArtifactsDir().toPath().resolve("result.txt"); + assertTrue("ArtifactArchiver is executed even prior publisher fails", Files.exists(path)); + assertEquals("Third publisher must see FAILURE status", Files.readString(path, StandardCharsets.UTF_8), Result.FAILURE.toString()); } /** @@ -89,8 +89,8 @@ public class FreestyleJobPublisherTest { j.assertLogContains("\tat hudson.model.utils.IOExceptionPublisher", b); // log must contain stacktrace j.assertLogContains("Threw IOException from publisher!", b); // log must contain exact error message - File file = new File(b.getArtifactsDir(), "result.txt"); - assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists()); - assertEquals("Third publisher must see FAILURE status", FileUtils.readFileToString(file, StandardCharsets.UTF_8), Result.FAILURE.toString()); + Path path = b.getArtifactsDir().toPath().resolve("result.txt"); + assertTrue("ArtifactArchiver is executed even prior publisher fails", Files.exists(path)); + assertEquals("Third publisher must see FAILURE status", Files.readString(path, StandardCharsets.UTF_8), Result.FAILURE.toString()); } } diff --git a/test/src/test/java/hudson/model/ItemGroupMixInTest.java b/test/src/test/java/hudson/model/ItemGroupMixInTest.java index db80be293e..5363d69dcb 100644 --- a/test/src/test/java/hudson/model/ItemGroupMixInTest.java +++ b/test/src/test/java/hudson/model/ItemGroupMixInTest.java @@ -50,11 +50,12 @@ import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import java.util.Collection; import java.util.List; import java.util.Map; import jenkins.model.Jenkins; -import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -96,13 +97,13 @@ public class ItemGroupMixInTest { File configFile = project.getConfigFile().getFile(); - List lines = FileUtils.readLines(configFile, StandardCharsets.UTF_8).subList(0, 5); + List lines = Files.readAllLines(configFile.toPath(), StandardCharsets.UTF_8).subList(0, 5); configFile.delete(); // Remove half of the config.xml file to make "invalid" or fail to load - FileUtils.writeByteArrayToFile(configFile, lines.toString().getBytes(StandardCharsets.UTF_8)); + Files.writeString(configFile.toPath(), lines.toString(), StandardCharsets.UTF_8); for (int i = lines.size() / 2; i < lines.size(); i++) { - FileUtils.writeStringToFile(configFile, lines.get(i), StandardCharsets.UTF_8, true); + Files.writeString(configFile.toPath(), lines.get(i), StandardCharsets.UTF_8, StandardOpenOption.APPEND); } // Reload Jenkins. diff --git a/test/src/test/java/hudson/model/QueueTest.java b/test/src/test/java/hudson/model/QueueTest.java index efae2285e2..85ba24bbc4 100644 --- a/test/src/test/java/hudson/model/QueueTest.java +++ b/test/src/test/java/hudson/model/QueueTest.java @@ -105,6 +105,7 @@ import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -133,7 +134,6 @@ import org.acegisecurity.acls.sid.PrincipalSid; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.io.FileUtils; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletHandler; @@ -178,7 +178,7 @@ public class QueueTest { assertNotNull(testProject.scheduleBuild2(0, new UserIdCause())); q.save(); - System.out.println(FileUtils.readFileToString(new File(r.jenkins.getRootDir(), "queue.xml"), StandardCharsets.UTF_8)); + System.out.println(Files.readString(r.jenkins.getRootDir().toPath().resolve("queue.xml"), StandardCharsets.UTF_8)); assertEquals(1, q.getItems().length); q.clear(); @@ -226,7 +226,7 @@ public class QueueTest { assertNotNull(testProject.scheduleBuild2(0, new UserIdCause())); q.save(); - System.out.println(FileUtils.readFileToString(new File(r.jenkins.getRootDir(), "queue.xml"))); + System.out.println(Files.readString(r.jenkins.getRootDir().toPath().resolve("queue.xml"), StandardCharsets.UTF_8)); assertEquals(1, q.getItems().length); q.clear(); diff --git a/test/src/test/java/hudson/model/UpdateSiteTest.java b/test/src/test/java/hudson/model/UpdateSiteTest.java index 946e42df59..c7d14ddcf6 100644 --- a/test/src/test/java/hudson/model/UpdateSiteTest.java +++ b/test/src/test/java/hudson/model/UpdateSiteTest.java @@ -38,6 +38,8 @@ import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -50,7 +52,6 @@ import javax.servlet.http.HttpServletResponse; import jenkins.model.Jenkins; import jenkins.security.UpdateSiteWarningsConfiguration; import jenkins.security.UpdateSiteWarningsMonitor; -import org.apache.commons.io.FileUtils; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; @@ -72,7 +73,7 @@ public class UpdateSiteTest { private String getResource(String resourceName) throws IOException { try { URL url = UpdateSiteTest.class.getResource(resourceName); - return url != null ? FileUtils.readFileToString(new File(url.toURI())) : null; + return url != null ? Files.readString(Paths.get(url.toURI()), StandardCharsets.UTF_8) : null; } catch (URISyntaxException e) { return null; } diff --git a/test/src/test/java/hudson/model/UserPropertyTest.java b/test/src/test/java/hudson/model/UserPropertyTest.java index 63d53a25d0..f7548e4c19 100644 --- a/test/src/test/java/hudson/model/UserPropertyTest.java +++ b/test/src/test/java/hudson/model/UserPropertyTest.java @@ -2,7 +2,6 @@ package hudson.model; import static java.lang.System.currentTimeMillis; import static java.util.Collections.emptyMap; -import static org.apache.commons.io.FileUtils.writeStringToFile; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @@ -12,9 +11,11 @@ import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import java.util.Collections; import java.util.List; -import org.apache.commons.io.FileUtils; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; @@ -78,7 +79,7 @@ public class UserPropertyTest { SetUserUserProperty property = user.getProperty(SetUserUserProperty.class); File testFile = property.getInnerUserClass().userFile; - List fileLines = FileUtils.readLines(testFile); + List fileLines = Files.readAllLines(testFile.toPath(), StandardCharsets.US_ASCII); assertThat(fileLines, hasSize(1)); j.configRoundtrip(user); @@ -86,7 +87,7 @@ public class UserPropertyTest { user = User.get("nestedUserReference", false, Collections.emptyMap()); assertThat("nested reference should exist after user configuration change", user, nestedUserSet()); - fileLines = FileUtils.readLines(testFile); + fileLines = Files.readAllLines(testFile.toPath(), StandardCharsets.US_ASCII); assertThat(fileLines, hasSize(1)); } @@ -182,7 +183,7 @@ public class UserPropertyTest { this.user = user; try { File userFile = getUserFile(); - writeStringToFile(userFile, String.valueOf(currentTimeMillis()), true); + Files.writeString(userFile.toPath(), String.valueOf(currentTimeMillis()), StandardCharsets.US_ASCII, StandardOpenOption.APPEND); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/test/src/test/java/hudson/util/BootFailureTest.java b/test/src/test/java/hudson/util/BootFailureTest.java index 1ce1cbc023..680c1178ff 100644 --- a/test/src/test/java/hudson/util/BootFailureTest.java +++ b/test/src/test/java/hudson/util/BootFailureTest.java @@ -11,13 +11,14 @@ import hudson.model.listeners.ItemListener; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import jenkins.model.Jenkins; -import org.apache.commons.io.FileUtils; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.junit.After; import org.junit.Rule; @@ -121,11 +122,11 @@ public class BootFailureTest { j.with(() -> home); // creates a script - FileUtils.write(new File(home, "boot-failure.groovy"), "hudson.util.BootFailureTest.problem = exception", StandardCharsets.UTF_8); - File d = new File(home, "boot-failure.groovy.d"); - d.mkdirs(); - FileUtils.write(new File(d, "1.groovy"), "hudson.util.BootFailureTest.runRecord << '1'", StandardCharsets.UTF_8); - FileUtils.write(new File(d, "2.groovy"), "hudson.util.BootFailureTest.runRecord << '2'", StandardCharsets.UTF_8); + Files.writeString(home.toPath().resolve("boot-failure.groovy"), "hudson.util.BootFailureTest.problem = exception", StandardCharsets.UTF_8); + Path d = home.toPath().resolve("boot-failure.groovy.d"); + Files.createDirectory(d); + Files.writeString(d.resolve("1.groovy"), "hudson.util.BootFailureTest.runRecord << '1'", StandardCharsets.UTF_8); + Files.writeString(d.resolve("2.groovy"), "hudson.util.BootFailureTest.runRecord << '2'", StandardCharsets.UTF_8); // first failed boot makeBootFail = true; @@ -157,9 +158,9 @@ public class BootFailureTest { public void interruptedStartup() throws Exception { final File home = tmpDir.newFolder(); j.with(() -> home); - File d = new File(home, "boot-failure.groovy.d"); - d.mkdirs(); - FileUtils.write(new File(d, "1.groovy"), "hudson.util.BootFailureTest.runRecord << '1'", StandardCharsets.UTF_8); + Path d = home.toPath().resolve("boot-failure.groovy.d"); + Files.createDirectory(d); + Files.writeString(d.resolve("1.groovy"), "hudson.util.BootFailureTest.runRecord << '1'", StandardCharsets.UTF_8); j.newHudson(); assertEquals(List.of("1"), runRecord); } diff --git a/test/src/test/java/hudson/util/XStream2AnnotationTest.java b/test/src/test/java/hudson/util/XStream2AnnotationTest.java index 6a85ad78a0..8a01255440 100644 --- a/test/src/test/java/hudson/util/XStream2AnnotationTest.java +++ b/test/src/test/java/hudson/util/XStream2AnnotationTest.java @@ -31,8 +31,8 @@ import com.thoughtworks.xstream.annotations.XStreamAlias; import hudson.ExtensionList; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import jenkins.model.GlobalConfiguration; -import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsSessionRule; @@ -108,7 +108,7 @@ public class XStream2AnnotationTest { } void writeXml(String xml) throws IOException { - FileUtils.write(getConfigFile().getFile(), xml, StandardCharsets.UTF_8); + Files.writeString(getConfigFile().getFile().toPath(), xml, StandardCharsets.UTF_8); } } diff --git a/test/src/test/java/hudson/util/XStream2Security383Test.java b/test/src/test/java/hudson/util/XStream2Security383Test.java index 84d5fc0b7a..2d8002eb4a 100644 --- a/test/src/test/java/hudson/util/XStream2Security383Test.java +++ b/test/src/test/java/hudson/util/XStream2Security383Test.java @@ -9,11 +9,11 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.logging.Level; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import jenkins.security.ClassFilterImpl; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.After; import org.junit.Before; @@ -74,7 +74,8 @@ public class XStream2Security383Test { exploitXml = exploitXml.replace("@TOKEN@", exploitFile.getAbsolutePath()); - FileUtils.write(new File(tempJobDir, "config.xml"), exploitXml, StandardCharsets.UTF_8); + Files.createDirectory(tempJobDir.toPath()); + Files.writeString(tempJobDir.toPath().resolve("config.xml"), exploitXml, StandardCharsets.UTF_8); assertThrows(IOException.class, () -> Items.load(j.jenkins, tempJobDir)); assertFalse("no file should be created here", exploitFile.exists()); diff --git a/test/src/test/java/jenkins/install/SetupWizardRestartTest.java b/test/src/test/java/jenkins/install/SetupWizardRestartTest.java index 8010862f90..edbc196d19 100644 --- a/test/src/test/java/jenkins/install/SetupWizardRestartTest.java +++ b/test/src/test/java/jenkins/install/SetupWizardRestartTest.java @@ -4,7 +4,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import hudson.Main; -import org.apache.commons.io.FileUtils; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -23,7 +24,7 @@ public class SetupWizardRestartTest { sessions.then(j -> { // Modify state so that we get into the same conditions as a real start Main.isUnitTest = false; - FileUtils.write(InstallUtil.getLastExecVersionFile(), ""); + Files.writeString(InstallUtil.getLastExecVersionFile().toPath(), "", StandardCharsets.US_ASCII); // Re-evaluate current state based on the new context InstallUtil.proceedToNextStateFrom(InstallState.UNKNOWN); assertEquals("Unexpected install state", InstallState.NEW, j.jenkins.getInstallState()); diff --git a/test/src/test/java/jenkins/install/SetupWizardTest.java b/test/src/test/java/jenkins/install/SetupWizardTest.java index a966e59d1c..07577480b3 100644 --- a/test/src/test/java/jenkins/install/SetupWizardTest.java +++ b/test/src/test/java/jenkins/install/SetupWizardTest.java @@ -42,6 +42,8 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; @@ -54,7 +56,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jenkins.model.Jenkins; import jenkins.util.JSONSignatureValidator; -import org.apache.commons.io.FileUtils; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; @@ -184,11 +185,11 @@ public class SetupWizardTest { } public void init() throws IOException { - File newFile = new File(tmpdir, "platform-plugins.json"); - FileUtils.write(newFile, "[ { " + Path newPath = tmpdir.toPath().resolve("platform-plugins.json"); + Files.writeString(newPath, "[ { " + "\"category\":\"Organization and Administration\", " + "\"plugins\": [ { \"name\": \"antisamy-markup-formatter\" } ]" - + "} ]"); + + "} ]", StandardCharsets.UTF_8); } } @@ -202,11 +203,11 @@ public class SetupWizardTest { } public void init() throws IOException { - File newFile = new File(tmpdir, "platform-plugins.json"); - FileUtils.write(newFile, "{ \"categories\" : [ { " + Path newPath = tmpdir.toPath().resolve("platform-plugins.json"); + Files.writeString(newPath, "{ \"categories\" : [ { " + "\"category\":\"Administration and Organization\", " + "\"plugins\": [ { \"name\": \"dashboard-view\"} ]" - + "} ] }"); + + "} ] }", StandardCharsets.UTF_8); } } diff --git a/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java b/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java index c3f476e6a4..38bb125331 100644 --- a/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java +++ b/test/src/test/java/jenkins/model/JenkinsBuildsAndWorkspacesDirectoriesTest.java @@ -13,12 +13,14 @@ import hudson.init.InitMilestone; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.stream.Stream; -import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -152,10 +154,10 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest { assertTrue(story.j.getInstance().isDefaultBuildDir()); // Now screw up the value by writing into the file directly, like one could do using external XML manipulation tools - final File configFile = new File(rule.jenkins.getRootDir(), "config.xml"); - final String screwedUp = FileUtils.readFileToString(configFile). + final Path configFile = rule.jenkins.getRootDir().toPath().resolve("config.xml"); + final String screwedUp = Files.readString(configFile, StandardCharsets.UTF_8). replaceFirst(".*", "eeeeeeeeek"); - FileUtils.write(configFile, screwedUp); + Files.writeString(configFile, screwedUp, StandardCharsets.UTF_8); }); story.thenDoesNotStart(); @@ -241,7 +243,7 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest { // ** HACK AROUND JENKINS-50422: manually restarting ** // // Check the disk (cannot just restart normally with the rule, ) - assertThat(FileUtils.readFileToString(new File(j.jenkins.getRootDir(), "config.xml")), + assertThat(Files.readString(j.jenkins.getRootDir().toPath().resolve("config.xml"), StandardCharsets.UTF_8), containsString("" + newBuildsDirValueBySysprop + "")); String rootDirBeforeRestart = j.jenkins.getRootDir().toString(); @@ -254,7 +256,7 @@ public class JenkinsBuildsAndWorkspacesDirectoriesTest { } assertEquals(rootDirBeforeRestart, j.jenkins.getRootDir().toString()); - assertThat(FileUtils.readFileToString(new File(j.jenkins.getRootDir(), "config.xml")), + assertThat(Files.readString(j.jenkins.getRootDir().toPath().resolve("config.xml"), StandardCharsets.UTF_8), containsString("" + newBuildsDirValueBySysprop + "")); assertEquals(newBuildsDirValueBySysprop, j.jenkins.getRawBuildsDir()); // ** END HACK ** // diff --git a/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java b/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java index 7e3f40d14c..e18b02b74e 100644 --- a/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java +++ b/test/src/test/java/jenkins/model/JenkinsLocationConfigurationTest.java @@ -16,12 +16,12 @@ import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.model.FreeStyleProject; import hudson.model.Label; -import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.atomic.AtomicReference; -import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -77,8 +77,8 @@ public class JenkinsLocationConfigurationTest { // no impact on the url in memory assertNull(JenkinsLocationConfiguration.getOrDie().getUrl()); - File configFile = new File(j.jenkins.getRootDir(), "jenkins.model.JenkinsLocationConfiguration.xml"); - String configFileContent = FileUtils.readFileToString(configFile, StandardCharsets.UTF_8); + Path configFile = j.jenkins.getRootDir().toPath().resolve("jenkins.model.JenkinsLocationConfiguration.xml"); + String configFileContent = Files.readString(configFile, StandardCharsets.UTF_8); assertThat(configFileContent, containsString("JenkinsLocationConfiguration")); assertThat(configFileContent, not(containsString("javascript:alert(123);//"))); } @@ -103,8 +103,8 @@ public class JenkinsLocationConfigurationTest { // the method ensures there is an trailing slash assertEquals(expectedUrl + "/", JenkinsLocationConfiguration.getOrDie().getUrl()); - File configFile = new File(j.jenkins.getRootDir(), "jenkins.model.JenkinsLocationConfiguration.xml"); - String configFileContent = FileUtils.readFileToString(configFile, StandardCharsets.UTF_8); + Path configFile = j.jenkins.getRootDir().toPath().resolve("jenkins.model.JenkinsLocationConfiguration.xml"); + String configFileContent = Files.readString(configFile, StandardCharsets.UTF_8); assertThat(configFileContent, containsString("JenkinsLocationConfiguration")); assertThat(configFileContent, containsString(expectedUrl)); } diff --git a/test/src/test/java/jenkins/model/PeepholePermalinkTest.java b/test/src/test/java/jenkins/model/PeepholePermalinkTest.java index 0273e014fb..8d06ab9801 100644 --- a/test/src/test/java/jenkins/model/PeepholePermalinkTest.java +++ b/test/src/test/java/jenkins/model/PeepholePermalinkTest.java @@ -8,6 +8,7 @@ import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Job; import hudson.model.Run; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.logging.Level; import org.junit.Rule; @@ -81,7 +82,7 @@ public class PeepholePermalinkTest { } private void assertStorage(String id, Job job, Run build) throws Exception { - assertThat(Files.readAllLines(PeepholePermalink.storageFor(job.getBuildDir()).toPath()), + assertThat(Files.readAllLines(PeepholePermalink.storageFor(job.getBuildDir()).toPath(), StandardCharsets.UTF_8), hasItem(id + " " + (build == null ? -1 : build.getNumber()))); } diff --git a/test/src/test/java/jenkins/security/ClassFilterImplTest.java b/test/src/test/java/jenkins/security/ClassFilterImplTest.java index b578980d14..9ccc33158c 100644 --- a/test/src/test/java/jenkins/security/ClassFilterImplTest.java +++ b/test/src/test/java/jenkins/security/ClassFilterImplTest.java @@ -49,11 +49,11 @@ import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.Map; import java.util.Set; import java.util.logging.Level; import jenkins.model.GlobalConfiguration; -import org.apache.commons.io.FileUtils; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; @@ -152,7 +152,7 @@ public class ClassFilterImplTest { config.save(); assertThat(config.getConfigFile().asString(), not(containsString("LinkedListMultimap"))); config.unrelated = "modified"; - FileUtils.write(config.getConfigFile().getFile(), new XStream().toXML(config), StandardCharsets.UTF_8); + Files.writeString(config.getConfigFile().getFile().toPath(), new XStream().toXML(config), StandardCharsets.UTF_8); assertThat(config.getConfigFile().asString(), allOf(containsString("LinkedListMultimap"), containsString("modified"))); config.obj = null; config.unrelated = null; diff --git a/test/src/test/java/jenkins/security/RekeySecretAdminMonitorTest.java b/test/src/test/java/jenkins/security/RekeySecretAdminMonitorTest.java index 0ff44e3a26..214560e118 100644 --- a/test/src/test/java/jenkins/security/RekeySecretAdminMonitorTest.java +++ b/test/src/test/java/jenkins/security/RekeySecretAdminMonitorTest.java @@ -22,11 +22,12 @@ import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Base64; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.crypto.Cipher; -import org.apache.commons.io.FileUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Before; @@ -89,13 +90,13 @@ public class RekeySecretAdminMonitorTest { private static void putSomeOldData(File dir) throws Exception { File xml = new File(dir, "foo.xml"); - FileUtils.writeStringToFile(xml, "" + encryptOld(TEST_KEY) + "", StandardCharsets.UTF_8); + Files.writeString(xml.toPath(), "" + encryptOld(TEST_KEY) + "", StandardCharsets.UTF_8); } private void verifyRewrite(File dir) throws Exception { - File xml = new File(dir, "foo.xml"); + Path xml = dir.toPath().resolve("foo.xml"); Pattern pattern = Pattern.compile("" + plain_regex_match + ""); - MatcherAssert.assertThat(FileUtils.readFileToString(xml, StandardCharsets.UTF_8).trim(), Matchers.matchesRegex(pattern)); + MatcherAssert.assertThat(Files.readString(xml, StandardCharsets.UTF_8).trim(), Matchers.matchesRegex(pattern)); } @WithTestSecret diff --git a/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProvider2Test.java b/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProvider2Test.java index be227cac60..c0e246fbe2 100644 --- a/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProvider2Test.java +++ b/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProvider2Test.java @@ -32,9 +32,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import java.io.File; import java.nio.charset.StandardCharsets; -import org.apache.commons.io.FileUtils; +import java.nio.file.Files; +import java.nio.file.Path; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.For; @@ -164,26 +164,26 @@ public class StaticRoutingDecisionProvider2Test { @Test public void userControlledWhitelist_savedCorrectly() throws Exception { - File whitelistUserControlledList = new File(j.jenkins.getRootDir(), "stapler-whitelist.txt"); + Path whitelistUserControlledList = j.jenkins.getRootDir().toPath().resolve("stapler-whitelist.txt"); - assertFalse(whitelistUserControlledList.exists()); + assertFalse(Files.exists(whitelistUserControlledList)); StaticRoutingDecisionProvider wl = new StaticRoutingDecisionProvider(); - assertFalse(whitelistUserControlledList.exists()); + assertFalse(Files.exists(whitelistUserControlledList)); assertThat(wl.decide("nothing"), is(RoutingDecisionProvider.Decision.UNKNOWN)); wl.save(); - assertTrue(whitelistUserControlledList.exists()); - assertThat(FileUtils.readFileToString(whitelistUserControlledList, StandardCharsets.UTF_8), is("")); + assertTrue(Files.exists(whitelistUserControlledList)); + assertThat(Files.readString(whitelistUserControlledList, StandardCharsets.UTF_8), is("")); wl.add("white-1"); assertThat(wl.decide("white-1"), is(RoutingDecisionProvider.Decision.ACCEPTED)); - assertTrue(whitelistUserControlledList.exists()); - assertThat(FileUtils.readFileToString(whitelistUserControlledList, StandardCharsets.UTF_8), containsString("white-1")); + assertTrue(Files.exists(whitelistUserControlledList)); + assertThat(Files.readString(whitelistUserControlledList, StandardCharsets.UTF_8), containsString("white-1")); { StaticRoutingDecisionProvider temp = new StaticRoutingDecisionProvider(); assertThat(temp.decide("white-1"), is(RoutingDecisionProvider.Decision.ACCEPTED)); @@ -193,7 +193,7 @@ public class StaticRoutingDecisionProvider2Test { assertThat(wl.decide("white-1"), is(RoutingDecisionProvider.Decision.ACCEPTED)); assertThat(wl.decide("black-2"), is(RoutingDecisionProvider.Decision.REJECTED)); - assertThat(FileUtils.readFileToString(whitelistUserControlledList, StandardCharsets.UTF_8), allOf( + assertThat(Files.readString(whitelistUserControlledList, StandardCharsets.UTF_8), allOf( containsString("white-1"), containsString("!black-2") )); @@ -208,7 +208,7 @@ public class StaticRoutingDecisionProvider2Test { assertThat(wl.decide("white-1"), is(RoutingDecisionProvider.Decision.ACCEPTED)); assertThat(wl.decide("black-2"), is(RoutingDecisionProvider.Decision.UNKNOWN)); - assertThat(FileUtils.readFileToString(whitelistUserControlledList, StandardCharsets.UTF_8), allOf( + assertThat(Files.readString(whitelistUserControlledList, StandardCharsets.UTF_8), allOf( containsString("white-1"), not(containsString("black-2")) )); @@ -223,7 +223,7 @@ public class StaticRoutingDecisionProvider2Test { assertThat(wl.decide("white-1"), is(RoutingDecisionProvider.Decision.UNKNOWN)); assertThat(wl.decide("black-2"), is(RoutingDecisionProvider.Decision.UNKNOWN)); - assertThat(FileUtils.readFileToString(whitelistUserControlledList, StandardCharsets.UTF_8), allOf( + assertThat(Files.readString(whitelistUserControlledList, StandardCharsets.UTF_8), allOf( not(containsString("white-1")), not(containsString("black-2")) )); diff --git a/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProviderTest.java b/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProviderTest.java index 64743b6d2a..9e849a2278 100644 --- a/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProviderTest.java +++ b/test/src/test/java/jenkins/security/stapler/StaticRoutingDecisionProviderTest.java @@ -30,12 +30,13 @@ import static org.junit.Assert.assertTrue; import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.ExtensionList; import hudson.model.FreeStyleProject; -import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Set; import jenkins.model.Jenkins; -import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -122,8 +123,8 @@ public class StaticRoutingDecisionProviderTest extends StaplerAbstractTest { @Test public void test_objectCustom_withUserControlledSavedWhitelist() throws Throwable { String whitelist = ContentProvider.OBJECT_CUSTOM_SIGNATURE + "\n"; - File whitelistFile = new File(j.jenkins.getRootDir(), "stapler-whitelist.txt"); - FileUtils.write(whitelistFile, whitelist); + Path whitelistFile = j.jenkins.getRootDir().toPath().resolve("stapler-whitelist.txt"); + Files.writeString(whitelistFile, whitelist, StandardCharsets.UTF_8); ExtensionList.lookupSingleton(StaticRoutingDecisionProvider.class).reload(); try { assertNotReachable("contentProvider/objectString/"); @@ -132,7 +133,7 @@ public class StaticRoutingDecisionProviderTest extends StaplerAbstractTest { assertReachable("contentProvider/objectCustom/"); assertTrue(ContentProvider.called); } finally { - whitelistFile.delete(); + Files.deleteIfExists(whitelistFile); ExtensionList.lookupSingleton(StaticRoutingDecisionProvider.class).reload(); } }