diff --git a/agent/src/main/java/com/thoughtworks/go/agent/AgentPluginsInitializer.java b/agent/src/main/java/com/thoughtworks/go/agent/AgentPluginsInitializer.java index 74f475d73e8d..84915aee153c 100644 --- a/agent/src/main/java/com/thoughtworks/go/agent/AgentPluginsInitializer.java +++ b/agent/src/main/java/com/thoughtworks/go/agent/AgentPluginsInitializer.java @@ -35,9 +35,9 @@ public class AgentPluginsInitializer implements ApplicationListener { private static final Logger LOG = LoggerFactory.getLogger(AgentPluginsInitializer.class); private final DefaultPluginJarLocationMonitor defaultPluginJarLocationMonitor; - private PluginManager pluginManager; - private ZipUtil zipUtil; - private SystemEnvironment systemEnvironment; + private final PluginManager pluginManager; + private final ZipUtil zipUtil; + private final SystemEnvironment systemEnvironment; @Autowired public AgentPluginsInitializer(PluginManager pluginManager, DefaultPluginJarLocationMonitor defaultPluginJarLocationMonitor, diff --git a/agent/src/test/java/com/thoughtworks/go/agent/service/AgentUpgradeServiceTest.java b/agent/src/test/java/com/thoughtworks/go/agent/service/AgentUpgradeServiceTest.java index 00693341c246..8c83349475fd 100644 --- a/agent/src/test/java/com/thoughtworks/go/agent/service/AgentUpgradeServiceTest.java +++ b/agent/src/test/java/com/thoughtworks/go/agent/service/AgentUpgradeServiceTest.java @@ -30,12 +30,12 @@ import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; import uk.org.webcompere.systemstubs.properties.SystemProperties; +import java.util.Base64; import java.util.Map; import java.util.Map.Entry; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toMap; -import static org.apache.commons.codec.binary.Base64.encodeBase64String; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.*; @@ -168,7 +168,7 @@ void checkForUpgradeShouldKillAgentIfTfsMd5doesNotMatch() { void shouldSetAnyExtraPropertiesSentByTheServer() throws Exception { setupForNoChangesToMD5(); - expectHeaderValue(SystemEnvironment.AGENT_EXTRA_PROPERTIES_HEADER, encodeBase64String("abc=def%20ghi jkl%20mno=pqr%20stu".getBytes(UTF_8))); + expectHeaderValue(SystemEnvironment.AGENT_EXTRA_PROPERTIES_HEADER, Base64.getEncoder().encodeToString("abc=def%20ghi jkl%20mno=pqr%20stu".getBytes(UTF_8))); agentUpgradeService.checkForUpgradeAndExtraProperties(); assertThat(System.getProperty("abc")).isEqualTo("def ghi"); @@ -181,7 +181,7 @@ void shouldFailQuietlyWhenExtraPropertiesHeaderValueIsInvalid() throws Exception final Map before = System.getProperties().entrySet().stream().collect(toMap(Entry::getKey, Entry::getValue)); - expectHeaderValue(SystemEnvironment.AGENT_EXTRA_PROPERTIES_HEADER, encodeBase64String("this_is_invalid".getBytes(UTF_8))); + expectHeaderValue(SystemEnvironment.AGENT_EXTRA_PROPERTIES_HEADER, Base64.getEncoder().encodeToString("this_is_invalid".getBytes(UTF_8))); agentUpgradeService.checkForUpgradeAndExtraProperties(); final Map after = System.getProperties().entrySet().stream().collect(toMap(Entry::getKey, Entry::getValue)); diff --git a/api/api-version-infos-v1/src/test/groovy/com/thoughtworks/go/apiv1/versioninfos/models/EncryptionHelperTest.java b/api/api-version-infos-v1/src/test/groovy/com/thoughtworks/go/apiv1/versioninfos/models/EncryptionHelperTest.java index da8bf75f1cdb..9784763ee256 100644 --- a/api/api-version-infos-v1/src/test/groovy/com/thoughtworks/go/apiv1/versioninfos/models/EncryptionHelperTest.java +++ b/api/api-version-infos-v1/src/test/groovy/com/thoughtworks/go/apiv1/versioninfos/models/EncryptionHelperTest.java @@ -18,7 +18,9 @@ import org.junit.jupiter.api.Test; import java.io.IOException; +import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -45,6 +47,8 @@ void shouldNotVerifyInvalidSignatureOrInvalidSubordinatePublicKeyWithMasterPubli } private String contentFromResource(String name) throws IOException { - return new String(getClass().getClassLoader().getResourceAsStream(name).readAllBytes(), StandardCharsets.UTF_8); + try (InputStream is = Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(name))) { + return new String(is.readAllBytes(), StandardCharsets.UTF_8); + } } } diff --git a/api/api-webhook-v1/src/test/groovy/com/thoughtworks/go/apiv1/webhook/helpers/PostHelper.java b/api/api-webhook-v1/src/test/groovy/com/thoughtworks/go/apiv1/webhook/helpers/PostHelper.java index 1440b864d215..d9d2560a6804 100644 --- a/api/api-webhook-v1/src/test/groovy/com/thoughtworks/go/apiv1/webhook/helpers/PostHelper.java +++ b/api/api-webhook-v1/src/test/groovy/com/thoughtworks/go/apiv1/webhook/helpers/PostHelper.java @@ -43,8 +43,8 @@ public interface PostHelper { static Map load(String resource) { final String json; - try (InputStream resourceAsStream = PostHelper.class.getResourceAsStream(resource)) { - json = new String(Objects.requireNonNull(resourceAsStream).readAllBytes(), StandardCharsets.UTF_8); + try (InputStream resourceAsStream = Objects.requireNonNull(PostHelper.class.getResourceAsStream(resource))) { + json = new String(resourceAsStream.readAllBytes(), StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/base/src/main/java/com/thoughtworks/go/agent/common/ssl/GoAgentServerClientBuilder.java b/base/src/main/java/com/thoughtworks/go/agent/common/ssl/GoAgentServerClientBuilder.java index 2b60a80244cd..e1c0a10597f3 100644 --- a/base/src/main/java/com/thoughtworks/go/agent/common/ssl/GoAgentServerClientBuilder.java +++ b/base/src/main/java/com/thoughtworks/go/agent/common/ssl/GoAgentServerClientBuilder.java @@ -17,7 +17,6 @@ import com.thoughtworks.go.util.SslVerificationMode; import com.thoughtworks.go.util.SystemEnvironment; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -32,6 +31,7 @@ import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; @@ -129,7 +129,7 @@ private List agentCertificate() throws IOException, Certificate private char[] passphrase() throws IOException { if (sslPrivateKeyPassphraseFile != null && sslPrivateKeyPassphraseFile.exists()) { - String passphrase = FileUtils.readFileToString(sslPrivateKeyPassphraseFile, StandardCharsets.UTF_8); + String passphrase = Files.readString(sslPrivateKeyPassphraseFile.toPath(), StandardCharsets.UTF_8); return StringUtils.trimToEmpty(passphrase).toCharArray(); } throw new RuntimeException("SSL private key passphrase not specified!"); diff --git a/base/src/main/java/com/thoughtworks/go/util/FileUtil.java b/base/src/main/java/com/thoughtworks/go/util/FileUtil.java index 85e6fd6292c7..d2651cb8f56d 100644 --- a/base/src/main/java/com/thoughtworks/go/util/FileUtil.java +++ b/base/src/main/java/com/thoughtworks/go/util/FileUtil.java @@ -15,21 +15,18 @@ */ package com.thoughtworks.go.util; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URI; +import java.nio.file.Files; import java.util.UUID; public class FileUtil { public static final String TMP_PARENT_DIR = "data"; private static final String CRUISE_TMP_FOLDER = "cruise" + "-" + UUID.randomUUID(); - private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class); private FileUtil() {} @@ -66,7 +63,7 @@ public static void validateAndCreateDirectory(File directory) { return; } try { - FileUtils.forceMkdir(directory); + Files.createDirectories(directory.toPath()); } catch (IOException e) { throw new RuntimeException("Failed to create folder: " + directory.getAbsolutePath()); } @@ -138,25 +135,6 @@ public static String getCanonicalPath(File workDir) { } } - public static void deleteDirectoryNoisily(File defaultDirectory) { - if (!defaultDirectory.exists()) { - return; - } - - try { - FileUtils.deleteDirectory(defaultDirectory); - } catch (IOException e) { - throw new RuntimeException("Failed to delete directory: " + defaultDirectory.getAbsolutePath(), e); - } - } - - public static String join(File defaultWorkingDir, String actualFileToUse) { - if (actualFileToUse == null) { - LOGGER.trace("Using the default Directory->{}", defaultWorkingDir); - return FilenameUtils.separatorsToUnix(defaultWorkingDir.getPath()); - } - return applyBaseDirIfRelativeAndNormalize(defaultWorkingDir, new File(actualFileToUse)); - } } diff --git a/base/src/main/java/com/thoughtworks/go/util/ZipBuilder.java b/base/src/main/java/com/thoughtworks/go/util/ZipBuilder.java index 2fe73cb7f454..ca9a79ff44d0 100644 --- a/base/src/main/java/com/thoughtworks/go/util/ZipBuilder.java +++ b/base/src/main/java/com/thoughtworks/go/util/ZipBuilder.java @@ -23,16 +23,12 @@ import java.util.Map; import java.util.zip.ZipOutputStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ZipBuilder { - private static final Logger LOGGER = LoggerFactory.getLogger(ZipBuilder.class); + private final ZipUtil zipUtil; + private final OutputStream destinationStream; + private final boolean excludeRootDir; private final int level; - private ZipUtil zipUtil; - private OutputStream destinationStream; - private boolean excludeRootDir; - private Map toAdd = new HashMap<>(); + private final Map toAdd = new HashMap<>(); public ZipBuilder(ZipUtil zipUtil, int level, OutputStream destinationStream, boolean excludeRootDir) { this.zipUtil = zipUtil; @@ -47,9 +43,7 @@ public ZipBuilder add(String directoryNameInsideZip, File sourceToZip) { } public void done() throws IOException { - ZipOutputStream zip = null; - try { - zip = new ZipOutputStream(new BufferedOutputStream(destinationStream)); + try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(destinationStream))) { zip.setLevel(level); for (Map.Entry zipDirToSourceFileEntry : toAdd.entrySet()) { File sourceFileToZip = zipDirToSourceFileEntry.getValue(); @@ -57,14 +51,6 @@ public void done() throws IOException { zipUtil.addToZip(new ZipPath(destinationFolder), sourceFileToZip, zip, excludeRootDir); } zip.flush(); - } finally { - if (zip != null) { - try { - zip.close(); - } catch (IOException e) { - LOGGER.error("Failed to close the stream", e); - } - } } } } diff --git a/commandline/src/main/java/com/thoughtworks/go/util/ProcessWrapper.java b/commandline/src/main/java/com/thoughtworks/go/util/ProcessWrapper.java index b1e575d0587c..f767e63be461 100644 --- a/commandline/src/main/java/com/thoughtworks/go/util/ProcessWrapper.java +++ b/commandline/src/main/java/com/thoughtworks/go/util/ProcessWrapper.java @@ -15,18 +15,19 @@ */ package com.thoughtworks.go.util; -import com.thoughtworks.go.util.command.*; -import org.apache.commons.io.IOUtils; +import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer; +import com.thoughtworks.go.util.command.ErrorConsumer; +import com.thoughtworks.go.util.command.OutputConsumer; +import com.thoughtworks.go.util.command.StreamPumper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; +import java.io.*; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.Objects; public class ProcessWrapper { @@ -51,14 +52,17 @@ public class ProcessWrapper { public int waitForExit() { int returnValue = -1; - try { + try (InputStream ignored = process.getInputStream(); + InputStream ignored1 = process.getErrorStream(); + OutputStream ignored2 = process.getOutputStream()) { + returnValue = process.waitFor(); processOutputStream.readToEnd(); processErrorStream.readToEnd(); - } catch (InterruptedException ignored) { - LOGGER.warn(ignored.getMessage(), ignored); + } catch (InterruptedException | IOException ignored) { } finally { - close(); + process.destroy(); + ProcessManager.getInstance().processKilled(process); } return returnValue; } @@ -71,7 +75,6 @@ public void typeInputToConsole(List inputs) { processInputStream.close(); } - private long lastHeardTime() { if (processErrorStream == null & processOutputStream == null) { return System.currentTimeMillis(); @@ -85,16 +88,10 @@ private long lastHeardTime() { return Math.min(processOutputStream.getLastHeard(), processErrorStream.getLastHeard()); } - public void closeOutputStream() throws IOException { process.getOutputStream().close(); } - public void close() { - close(process); - ProcessManager.getInstance().processKilled(process); - } - public boolean isRunning() { try { process.exitValue(); @@ -131,11 +128,7 @@ public boolean equals(Object o) { ProcessWrapper that = (ProcessWrapper) o; - if (process != null ? !process.equals(that.process) : that.process != null) { - return false; - } - - return true; + return Objects.equals(process, that.process); } @Override @@ -143,16 +136,4 @@ public int hashCode() { return process != null ? process.hashCode() : 0; } - private void close(Process p) { - try { - IOUtils.closeQuietly(p.getInputStream()); - IOUtils.closeQuietly(p.getOutputStream()); - IOUtils.closeQuietly(p.getErrorStream()); - } finally { - if (p != null) { - p.destroy(); - } - } - } - } diff --git a/commandline/src/main/java/com/thoughtworks/go/util/command/StreamPumper.java b/commandline/src/main/java/com/thoughtworks/go/util/command/StreamPumper.java index 6bc48d685eaf..1b74fe183353 100644 --- a/commandline/src/main/java/com/thoughtworks/go/util/command/StreamPumper.java +++ b/commandline/src/main/java/com/thoughtworks/go/util/command/StreamPumper.java @@ -34,11 +34,10 @@ public class StreamPumper implements Runnable { - private Reader in; - - private boolean completed; + private final Reader in; private final StreamConsumer streamConsumer; private final String prefix; + private boolean completed; private long lastHeard; private final Clock clock; diff --git a/common/build.gradle b/common/build.gradle index 38323ebb68d1..4c8f731ba8f4 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -28,6 +28,7 @@ dependencies { api project.deps.commonsCollections4 api project.deps.commonsText api project.deps.springTx + implementation project.deps.commonsIO implementation project.deps.jodaTime annotationProcessor project.deps.lombok compileOnly project.deps.lombok diff --git a/common/src/test/java/com/thoughtworks/go/agent/testhelpers/DefaultWorkCreator.java b/common/src/test/java/com/thoughtworks/go/agent/testhelpers/DefaultWorkCreator.java index 17fe9b63f032..49475b607b50 100644 --- a/common/src/test/java/com/thoughtworks/go/agent/testhelpers/DefaultWorkCreator.java +++ b/common/src/test/java/com/thoughtworks/go/agent/testhelpers/DefaultWorkCreator.java @@ -29,12 +29,12 @@ import com.thoughtworks.go.remote.work.BuildWork; import com.thoughtworks.go.remote.work.Work; import com.thoughtworks.go.util.SystemEnvironment; -import com.thoughtworks.go.util.TestFileUtil; import com.thoughtworks.go.util.command.EnvironmentVariableContext; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.ArrayList; import java.util.List; @@ -51,7 +51,7 @@ public class DefaultWorkCreator implements WorkCreator { private static File tempFile() { try { - File tempFile = TestFileUtil.createTempFile("artifact.tmp"); + File tempFile = Files.createTempFile("artifact", "artifact.tmp").toFile(); tempFile.deleteOnExit(); return tempFile; } catch (IOException e) { diff --git a/common/src/test/java/com/thoughtworks/go/agent/testhelpers/FakeBuildRepositoryRemote.java b/common/src/test/java/com/thoughtworks/go/agent/testhelpers/FakeBuildRepositoryRemote.java index 6cd3be4132d5..49dcf8a78293 100644 --- a/common/src/test/java/com/thoughtworks/go/agent/testhelpers/FakeBuildRepositoryRemote.java +++ b/common/src/test/java/com/thoughtworks/go/agent/testhelpers/FakeBuildRepositoryRemote.java @@ -29,9 +29,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; public class FakeBuildRepositoryRemote implements BuildRepositoryRemote { public final static List AGENT_STATUS = new ArrayList<>(); @@ -39,11 +36,7 @@ public class FakeBuildRepositoryRemote implements BuildRepositoryRemote { private static final Logger LOGGER = LoggerFactory.getLogger(FakeBuildRepositoryRemote.class); public static final String PIPELINE_NAME = "studios"; - public static final String PIPELINE_LABEL = "100"; public static final String STAGE_NAME = "pipeline"; - public static final String JOB_PLAN_NAME = "cruise-test-data"; - - private static final BlockingQueue buildResult = new LinkedBlockingQueue<>(); @Override public AgentInstruction ping(AgentRuntimeInfo info) { @@ -54,12 +47,10 @@ public AgentInstruction ping(AgentRuntimeInfo info) { @Override public Work getWork(AgentRuntimeInfo runtimeInfo) { String className = SystemEnvironment.getProperty("WORKCREATOR", DefaultWorkCreator.class.getCanonicalName()); - Class aClass = null; try { - aClass = (Class) Class.forName(className); + Class aClass = (Class) Class.forName(className); return aClass.getDeclaredConstructor().newInstance().work(runtimeInfo.getIdentifier()); } catch (Exception e) { - e.printStackTrace(); throw new RuntimeException(e); } } @@ -67,9 +58,6 @@ public Work getWork(AgentRuntimeInfo runtimeInfo) { @Override public void reportCurrentStatus(AgentRuntimeInfo agentRuntimeInfo, JobIdentifier jobIdentifier, JobState jobState) { LOGGER.info("Current status of build instance with id {} is {}", jobIdentifier, jobState); - if (jobState.isCompleted()) { - buildResult.offer(Boolean.TRUE); - } } @Override @@ -91,17 +79,4 @@ public boolean isIgnored(AgentRuntimeInfo agentRuntimeInfo, JobIdentifier jobIde public String getCookie(AgentRuntimeInfo agentRuntimeInfo) { throw new UnsupportedOperationException("Not implemented"); } - - public static void waitUntilBuildCompleted() throws InterruptedException { - while (!isBuildCompleted()) { - Thread.sleep(1000); - } - } - - private static boolean isBuildCompleted() throws InterruptedException { - Boolean aBoolean = buildResult.poll(1, TimeUnit.SECONDS); - return aBoolean != null && aBoolean; - } - - } diff --git a/common/src/test/java/com/thoughtworks/go/domain/materials/git/GitCommandTest.java b/common/src/test/java/com/thoughtworks/go/domain/materials/git/GitCommandTest.java index 7fb5ca00d587..652ae1f39f27 100644 --- a/common/src/test/java/com/thoughtworks/go/domain/materials/git/GitCommandTest.java +++ b/common/src/test/java/com/thoughtworks/go/domain/materials/git/GitCommandTest.java @@ -28,7 +28,6 @@ import com.thoughtworks.go.util.TempDirUtils; import com.thoughtworks.go.util.command.*; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; @@ -41,7 +40,7 @@ import java.io.File; import java.io.IOException; -import java.io.InputStream; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Date; @@ -697,10 +696,7 @@ void shouldThrowExceptionIfRepoCanNotConnectWhenModificationCheck() { @Test void shouldParseGitOutputCorrectly() throws IOException { - List stringList; - try (InputStream resourceAsStream = getClass().getResourceAsStream("git_sample_output.text")) { - stringList = IOUtils.readLines(resourceAsStream, UTF_8); - } + List stringList = Files.readAllLines(Path.of(getClass().getResource("git_sample_output.text").getPath())); GitModificationParser parser = new GitModificationParser(); List mods = parser.parse(stringList); diff --git a/config/config-api/build.gradle b/config/config-api/build.gradle index b95053fb37a5..e73142b44b11 100644 --- a/config/config-api/build.gradle +++ b/config/config-api/build.gradle @@ -27,6 +27,7 @@ dependencies { implementation project.deps.commonsCodec implementation project.deps.commonsCollections4 + implementation project.deps.commonsIO implementation project.deps.commonsText api(project.deps.quartz) { transitive = false diff --git a/base/src/main/java/com/thoughtworks/go/util/FilenameUtil.java b/config/config-api/src/main/java/com/thoughtworks/go/util/FilenameUtil.java similarity index 100% rename from base/src/main/java/com/thoughtworks/go/util/FilenameUtil.java rename to config/config-api/src/main/java/com/thoughtworks/go/util/FilenameUtil.java diff --git a/base/src/test/java/com/thoughtworks/go/util/FilenameUtilTest.java b/config/config-api/src/test/java/com/thoughtworks/go/util/FilenameUtilTest.java similarity index 100% rename from base/src/test/java/com/thoughtworks/go/util/FilenameUtilTest.java rename to config/config-api/src/test/java/com/thoughtworks/go/util/FilenameUtilTest.java diff --git a/config/config-server/src/main/java/com/thoughtworks/go/plugins/presentation/PluggableTaskViewModelFactory.java b/config/config-server/src/main/java/com/thoughtworks/go/plugins/presentation/PluggableTaskViewModelFactory.java index e7cdca303986..2f47edbce99f 100644 --- a/config/config-server/src/main/java/com/thoughtworks/go/plugins/presentation/PluggableTaskViewModelFactory.java +++ b/config/config-server/src/main/java/com/thoughtworks/go/plugins/presentation/PluggableTaskViewModelFactory.java @@ -71,7 +71,7 @@ private String getTemplate(final TaskView view) { } private String loadTemplateFromClasspath(final String filepath, final TaskView view) { - try(InputStream in = view.getClass().getResourceAsStream(filepath)) { + try (InputStream in = view.getClass().getResourceAsStream(filepath)) { return in != null ? new String(in.readAllBytes(), UTF_8) : String.format("Template \"%s\" is missing.", filepath); } catch (IOException e) { LOG.error("Failed to load template from view from path \"{}\". Make sure your the template is on the classpath of your plugin", filepath, e); diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/ConfigMigrator.java b/config/config-server/src/test/java/com/thoughtworks/go/config/ConfigMigrator.java index 4a98e70718cb..118909be874b 100644 --- a/config/config-server/src/test/java/com/thoughtworks/go/config/ConfigMigrator.java +++ b/config/config-server/src/test/java/com/thoughtworks/go/config/ConfigMigrator.java @@ -17,31 +17,31 @@ import com.thoughtworks.go.config.registry.ConfigElementImplementationRegistry; import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother; -import com.thoughtworks.go.util.TestFileUtil; import com.thoughtworks.go.util.TimeProvider; -import org.apache.commons.io.FileUtils; import java.io.ByteArrayInputStream; -import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import static java.nio.charset.StandardCharsets.UTF_8; public class ConfigMigrator { - public static GoConfigMigration migrate(final File configFile) { + public static GoConfigMigration migrate(final Path configFile) { ConfigElementImplementationRegistry registry = ConfigElementImplementationRegistryMother.withNoPlugins(); String content = ""; try { - content = FileUtils.readFileToString(configFile, UTF_8); - } catch (IOException e1) { + content = Files.readString(configFile, UTF_8); + } catch (IOException ignored) { } GoConfigMigration upgrader = new GoConfigMigration(new TimeProvider(), registry); //TODO: LYH & GL GoConfigMigration should be able to handle stream instead of binding to file String upgradedContent = upgrader.upgradeIfNecessary(content); try { - FileUtils.writeStringToFile(configFile, upgradedContent, UTF_8); + Files.writeString(configFile, upgradedContent, UTF_8); } catch (IOException e) { throw new RuntimeException(e); } @@ -49,11 +49,11 @@ public static GoConfigMigration migrate(final File configFile) { } public static String migrate(String configXml) throws IOException { - File tempFile = TestFileUtil.createTempFile("cruise-config.xml"); - FileUtils.writeStringToFile(tempFile, configXml, UTF_8); + Path tempFile = Files.createTempFile("cruise-config", ".xml"); + Files.writeString(tempFile, configXml, UTF_8); migrate(tempFile); - String newConfigXml = FileUtils.readFileToString(tempFile, UTF_8); - tempFile.delete(); + String newConfigXml = Files.readString(tempFile, UTF_8); + tempFile.toFile().delete(); return newConfigXml; } @@ -79,14 +79,14 @@ public static GoConfigHolder loadWithMigration(InputStream input) throws Excepti } public static GoConfigHolder loadWithMigration(InputStream input, final ConfigElementImplementationRegistry registry) throws Exception { - File tempFile = TestFileUtil.createTempFile("cruise-config.xml"); + Path tempFile = Files.createTempFile("cruise-config", ".xml"); try { MagicalGoConfigXmlLoader xmlLoader = new MagicalGoConfigXmlLoader(new ConfigCache(), registry); - FileUtils.copyInputStreamToFile(input, tempFile); + Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING); migrate(tempFile); - return xmlLoader.loadConfigHolder(FileUtils.readFileToString(tempFile, UTF_8)); + return xmlLoader.loadConfigHolder(Files.readString(tempFile, UTF_8)); } finally { - FileUtils.deleteQuietly(tempFile); + Files.deleteIfExists(tempFile); } } diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java index 227c1b4e4ede..8d3eeb9db0ca 100644 --- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java +++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java @@ -86,9 +86,11 @@ import org.junit.jupiter.api.extension.ExtendWith; import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Objects; import static com.thoughtworks.go.config.PipelineConfig.*; import static com.thoughtworks.go.domain.packagerepository.ConfigurationPropertyMother.create; @@ -990,8 +992,9 @@ void shouldNotAllowEmptyViewForPerforce() { } private String loadWithMigration(String resource) throws Exception { - String config = new String(this.getClass().getResourceAsStream(resource).readAllBytes(), UTF_8); - return goConfigMigration.upgradeIfNecessary(config); + try (InputStream is = Objects.requireNonNull(this.getClass().getResourceAsStream(resource))) { + return goConfigMigration.upgradeIfNecessary(new String(is.readAllBytes(), UTF_8)); + } } @Test @@ -4204,7 +4207,7 @@ void shouldEncryptPluggablePublishArtifactProperties() throws Exception { ArtifactPluginInfo artifactPluginInfo = new ArtifactPluginInfo(pluginDescriptor, storeConfigSettings, publishArtifactSettings, fetchArtifactSettings, null, new Capabilities()); ArtifactMetadataStore.instance().setPluginInfo(artifactPluginInfo); - String content = goConfigMigration.upgradeIfNecessary(new String(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml").readAllBytes(), UTF_8)); + String content = loadWithMigration("/data/pluggable_artifacts_with_params.xml"); CruiseConfig config = xmlLoader.loadConfigHolder(content).configForEdit; PipelineConfig ancestor = config.pipelineConfigByName(new CaseInsensitiveString("ancestor")); diff --git a/domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java b/domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java index 018265657b14..24cc854b1a32 100644 --- a/domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java +++ b/domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java @@ -36,6 +36,7 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter; import java.io.File; +import java.io.IOException; import java.net.URISyntaxException; import java.util.*; @@ -43,7 +44,6 @@ import static com.thoughtworks.go.util.ExceptionUtils.bomb; import static com.thoughtworks.go.util.ExceptionUtils.bombIfFailedToRunCommandLine; import static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist; -import static com.thoughtworks.go.util.FileUtil.deleteDirectoryNoisily; import static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer; import static java.lang.String.format; import static org.apache.commons.lang3.StringUtils.isAllBlank; @@ -358,7 +358,11 @@ private GitCommand git(ConsoleOutputStreamConsumer outputStreamConsumer, final F GitCommand gitCommand = new GitCommand(getFingerprint(), workingFolder, refSpecOrBranch, false, secrets()); if (!isGitRepository(workingFolder) || isRepositoryChanged(gitCommand, workingFolder)) { LOG.debug("Invalid git working copy or repository changed. Delete folder: {}", workingFolder); - deleteDirectoryNoisily(workingFolder); + try { + FileUtils.deleteDirectory(workingFolder); + } catch (IOException e) { + throw new RuntimeException("Failed to delete directory: " + workingFolder.getAbsolutePath(), e); + } } createParentFolderIfNotExist(workingFolder); if (!workingFolder.exists()) { diff --git a/config/config-api/src/main/java/com/thoughtworks/go/domain/UnitTestReportGenerator.java b/domain/src/main/java/com/thoughtworks/go/domain/UnitTestReportGenerator.java similarity index 97% rename from config/config-api/src/main/java/com/thoughtworks/go/domain/UnitTestReportGenerator.java rename to domain/src/main/java/com/thoughtworks/go/domain/UnitTestReportGenerator.java index 3e782ea01758..a0006df39002 100644 --- a/config/config-api/src/main/java/com/thoughtworks/go/domain/UnitTestReportGenerator.java +++ b/domain/src/main/java/com/thoughtworks/go/domain/UnitTestReportGenerator.java @@ -15,7 +15,7 @@ */ package com.thoughtworks.go.domain; -import com.thoughtworks.go.util.TestFileUtil; +import com.thoughtworks.go.util.TempFiles; import com.thoughtworks.go.util.XpathUtils; import com.thoughtworks.go.work.GoPublisher; import org.apache.commons.io.FileUtils; @@ -81,7 +81,7 @@ public void generate(File[] allTestFiles, String uploadDestPath) { } private File mergeAllTestResultToSingleFile(File[] allTestFiles) throws IOException { - File mergedResource = TestFileUtil.createUniqueTempFile("mergedFile.xml"); + File mergedResource = TempFiles.createUniqueFile("mergedFile.xml"); try (FileOutputStream mergedResourcesStream = new FileOutputStream(mergedResource)) { merge(allTestFiles, mergedResourcesStream); } diff --git a/base/src/main/java/com/thoughtworks/go/util/TempFiles.java b/domain/src/main/java/com/thoughtworks/go/util/TempFiles.java similarity index 95% rename from base/src/main/java/com/thoughtworks/go/util/TempFiles.java rename to domain/src/main/java/com/thoughtworks/go/util/TempFiles.java index 95950e5c9658..a1cdf52ca11c 100644 --- a/base/src/main/java/com/thoughtworks/go/util/TempFiles.java +++ b/domain/src/main/java/com/thoughtworks/go/util/TempFiles.java @@ -25,13 +25,12 @@ public class TempFiles { - private List createdFiles = new ArrayList<>(); + private final List createdFiles = new ArrayList<>(); private Clock clock; - private Runnable cleanupHook = this::cleanUp; - public TempFiles() { this.clock = new SystemTimeClock(); + Runnable cleanupHook = this::cleanUp; Runtime.getRuntime().addShutdownHook(new Thread(cleanupHook)); } diff --git a/common/src/main/resources/com/thoughtworks/go/domain/unittests.xsl b/domain/src/main/resources/com/thoughtworks/go/domain/unittests.xsl similarity index 100% rename from common/src/main/resources/com/thoughtworks/go/domain/unittests.xsl rename to domain/src/main/resources/com/thoughtworks/go/domain/unittests.xsl diff --git a/common/src/test/java/com/thoughtworks/go/domain/UnitTestReportGeneratorTest.java b/domain/src/test/java/com/thoughtworks/go/domain/UnitTestReportGeneratorTest.java similarity index 100% rename from common/src/test/java/com/thoughtworks/go/domain/UnitTestReportGeneratorTest.java rename to domain/src/test/java/com/thoughtworks/go/domain/UnitTestReportGeneratorTest.java diff --git a/base/src/test/java/com/thoughtworks/go/util/TempFilesTest.java b/domain/src/test/java/com/thoughtworks/go/util/TempFilesTest.java similarity index 93% rename from base/src/test/java/com/thoughtworks/go/util/TempFilesTest.java rename to domain/src/test/java/com/thoughtworks/go/util/TempFilesTest.java index f10c27308c56..e00030bb4815 100644 --- a/base/src/test/java/com/thoughtworks/go/util/TempFilesTest.java +++ b/domain/src/test/java/com/thoughtworks/go/util/TempFilesTest.java @@ -77,7 +77,7 @@ public void shouldDeleteNonEmptyFolders() throws IOException { } @Test - public void shouldForgetFolders() throws IOException { + public void shouldForgetFolders() { File file = files.mkdir("foo"); files.cleanUp(); @@ -97,7 +97,7 @@ private File tmpDir() { } @Test - public void shouldCreateDirsInTempDirectory() throws IOException { + public void shouldCreateDirsInTempDirectory() { File dir = files.mkdir("foo"); File parentFile = dir.getParentFile(); assertThat(parentFile.getName(), is("cruise")); @@ -105,7 +105,7 @@ public void shouldCreateDirsInTempDirectory() throws IOException { } @Test - public void shouldCreateUniqueFilesEveryTime() throws IOException { + public void shouldCreateUniqueFilesEveryTime() { TestingClock clock = new TestingClock(); files.setClock(clock); File file1 = files.createUniqueFile("foo"); @@ -114,7 +114,7 @@ public void shouldCreateUniqueFilesEveryTime() throws IOException { } @Test - public void shouldCreateUniqueFilesParentDirectoryIfDoesNotExist() throws IOException { + public void shouldCreateUniqueFilesParentDirectoryIfDoesNotExist() { String newTmpDir = original.getProperty("java.io.tmpdir") + "/" + UUID.randomUUID(); System.setProperty("java.io.tmpdir", newTmpDir); File file = files.createUniqueFile("foo"); @@ -122,7 +122,7 @@ public void shouldCreateUniqueFilesParentDirectoryIfDoesNotExist() throws IOExce } @Test - public void shouldCreateUniqueFolders() throws IOException { + public void shouldCreateUniqueFolders() { TestingClock clock = new TestingClock(); files.setClock(clock); File file1 = files.createUniqueFolder("foo"); diff --git a/common/src/test/resources/data/test-results/empty.xml b/domain/src/test/resources/data/test-results/empty.xml similarity index 100% rename from common/src/test/resources/data/test-results/empty.xml rename to domain/src/test/resources/data/test-results/empty.xml diff --git a/common/src/test/resources/data/test-results/invalid-nunit.xml b/domain/src/test/resources/data/test-results/invalid-nunit.xml similarity index 100% rename from common/src/test/resources/data/test-results/invalid-nunit.xml rename to domain/src/test/resources/data/test-results/invalid-nunit.xml diff --git a/common/src/test/resources/data/test-results/junit-minified-from-pytest-no-decl.xml b/domain/src/test/resources/data/test-results/junit-minified-from-pytest-no-decl.xml similarity index 100% rename from common/src/test/resources/data/test-results/junit-minified-from-pytest-no-decl.xml rename to domain/src/test/resources/data/test-results/junit-minified-from-pytest-no-decl.xml diff --git a/common/src/test/resources/data/test-results/junit-minified-from-pytest.xml b/domain/src/test/resources/data/test-results/junit-minified-from-pytest.xml similarity index 100% rename from common/src/test/resources/data/test-results/junit-minified-from-pytest.xml rename to domain/src/test/resources/data/test-results/junit-minified-from-pytest.xml diff --git a/common/src/test/resources/data/test-results/junit-result-four-tests.xml b/domain/src/test/resources/data/test-results/junit-result-four-tests.xml similarity index 100% rename from common/src/test/resources/data/test-results/junit-result-four-tests.xml rename to domain/src/test/resources/data/test-results/junit-result-four-tests.xml diff --git a/common/src/test/resources/data/test-results/junit-result-no-decl.xml b/domain/src/test/resources/data/test-results/junit-result-no-decl.xml similarity index 100% rename from common/src/test/resources/data/test-results/junit-result-no-decl.xml rename to domain/src/test/resources/data/test-results/junit-result-no-decl.xml diff --git a/common/src/test/resources/data/test-results/junit-result-single-test.xml b/domain/src/test/resources/data/test-results/junit-result-single-test.xml similarity index 100% rename from common/src/test/resources/data/test-results/junit-result-single-test.xml rename to domain/src/test/resources/data/test-results/junit-result-single-test.xml diff --git a/common/src/test/resources/data/test-results/ncover-report.xml b/domain/src/test/resources/data/test-results/ncover-report.xml similarity index 100% rename from common/src/test/resources/data/test-results/ncover-report.xml rename to domain/src/test/resources/data/test-results/ncover-report.xml diff --git a/common/src/test/resources/data/test-results/nunit-result-204.xml b/domain/src/test/resources/data/test-results/nunit-result-204.xml similarity index 100% rename from common/src/test/resources/data/test-results/nunit-result-204.xml rename to domain/src/test/resources/data/test-results/nunit-result-204.xml diff --git a/common/src/test/resources/data/test-results/nunit-result-206.xml b/domain/src/test/resources/data/test-results/nunit-result-206.xml similarity index 100% rename from common/src/test/resources/data/test-results/nunit-result-206.xml rename to domain/src/test/resources/data/test-results/nunit-result-206.xml diff --git a/common/src/test/resources/data/test-results/nunit-result-integration.xml b/domain/src/test/resources/data/test-results/nunit-result-integration.xml similarity index 100% rename from common/src/test/resources/data/test-results/nunit-result-integration.xml rename to domain/src/test/resources/data/test-results/nunit-result-integration.xml diff --git a/common/src/test/resources/data/test-results/nunit-result-unit.xml b/domain/src/test/resources/data/test-results/nunit-result-unit.xml similarity index 100% rename from common/src/test/resources/data/test-results/nunit-result-unit.xml rename to domain/src/test/resources/data/test-results/nunit-result-unit.xml diff --git a/jetty9/src/main/java/com/thoughtworks/go/server/Jetty9Server.java b/jetty9/src/main/java/com/thoughtworks/go/server/Jetty9Server.java index c19376782fb8..e5db25ffe94c 100644 --- a/jetty9/src/main/java/com/thoughtworks/go/server/Jetty9Server.java +++ b/jetty9/src/main/java/com/thoughtworks/go/server/Jetty9Server.java @@ -17,7 +17,6 @@ import com.thoughtworks.go.server.util.GoPlainSocketConnector; import com.thoughtworks.go.util.SystemEnvironment; -import org.apache.commons.io.FileUtils; import org.eclipse.jetty.deploy.App; import org.eclipse.jetty.deploy.DeploymentManager; import org.eclipse.jetty.deploy.providers.WebAppProvider; @@ -45,17 +44,20 @@ import java.io.IOException; import java.io.InputStream; import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.Objects; import static java.nio.charset.StandardCharsets.UTF_8; public class Jetty9Server extends AppServer { protected static String JETTY_XML_LOCATION_IN_JAR = "/defaultFiles/config"; + private static final Logger LOG = LoggerFactory.getLogger(Jetty9Server.class); private static final String JETTY_XML = "jetty.xml"; private static final String JETTY_CONFIG_VERSION = "jetty-v9.4.48.v20220622"; - private Server server; - private WebAppContext webAppContext; - private static final Logger LOG = LoggerFactory.getLogger(Jetty9Server.class); + private final Server server; private final DeploymentManager deploymentManager; + private WebAppContext webAppContext; public Jetty9Server(SystemEnvironment systemEnvironment) { this(systemEnvironment, new Server(), new DeploymentManager()); @@ -202,13 +204,13 @@ private void performCustomConfiguration() throws Exception { } protected void replaceJettyXmlIfItBelongsToADifferentVersion(File jettyConfig) throws IOException { - if (FileUtils.readFileToString(jettyConfig, UTF_8).contains(JETTY_CONFIG_VERSION)) return; + if (Files.readString(jettyConfig.toPath(), UTF_8).contains(JETTY_CONFIG_VERSION)) return; replaceFileWithPackagedOne(jettyConfig); } private void replaceFileWithPackagedOne(File jettyConfig) { - try (InputStream inputStream = getClass().getResourceAsStream(JETTY_XML_LOCATION_IN_JAR + "/" + jettyConfig.getName())) { - FileUtils.copyInputStreamToFile(inputStream, systemEnvironment.getJettyConfigFile()); + try (InputStream inputStream = Objects.requireNonNull(getClass().getResourceAsStream(JETTY_XML_LOCATION_IN_JAR + "/" + jettyConfig.getName()))) { + Files.copy(inputStream, systemEnvironment.getJettyConfigFile().toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException(e); } @@ -218,7 +220,7 @@ private String getWarFile() { return systemEnvironment.getCruiseWar(); } - private WebAppContext createWebAppContext() { + private void createWebAppContext() { webAppContext = new WebAppContext(); webAppContext.setDefaultsDescriptor(GoWebXmlConfiguration.configuration(getWarFile())); @@ -236,7 +238,6 @@ private WebAppContext createWebAppContext() { webAppContext.setWar(getWarFile()); webAppContext.setParentLoaderPriority(systemEnvironment.getParentLoaderPriority()); - return webAppContext; } public Server getServer() { diff --git a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java index 539afd599c75..484e1f2ccee6 100644 --- a/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java +++ b/plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java @@ -17,8 +17,10 @@ import com.bazaarvoice.jolt.JsonUtils; +import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Map; +import java.util.Objects; import static com.bazaarvoice.jolt.utils.JoltUtils.remove; import static com.bazaarvoice.jolt.utils.JoltUtils.store; @@ -40,8 +42,8 @@ String versionOneComprehensiveWithNoLocking() { } private Map getJSONFor(String fileName) { - try { - String transformJSON = new String(this.getClass().getResourceAsStream(fileName).readAllBytes(), StandardCharsets.UTF_8); + try (InputStream is = Objects.requireNonNull(this.getClass().getResourceAsStream(fileName))) { + String transformJSON = new String(is.readAllBytes(), StandardCharsets.UTF_8); return JsonUtils.jsonToMap(transformJSON); } catch (Exception e) { throw new RuntimeException(e); diff --git a/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/monitor/BundleOrPluginFileDetails.java b/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/monitor/BundleOrPluginFileDetails.java index 91b2523e6d62..fc00889d9ce7 100644 --- a/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/monitor/BundleOrPluginFileDetails.java +++ b/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/monitor/BundleOrPluginFileDetails.java @@ -18,7 +18,6 @@ import lombok.EqualsAndHashCode; import lombok.ToString; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; import java.io.File; @@ -86,7 +85,7 @@ private byte[] getEntryAsString(String jarFileEntry) { ZipEntry entry = jarFile.getEntry(jarFileEntry); if (entry != null) { try (InputStream inputStream = jarFile.getInputStream(entry)) { - return IOUtils.toByteArray(inputStream); + return inputStream.readAllBytes(); } } } catch (IOException e) { diff --git a/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginBundleDescriptorParser.java b/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginBundleDescriptorParser.java index 1ed798d1888b..bcddd151aafd 100644 --- a/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginBundleDescriptorParser.java +++ b/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginBundleDescriptorParser.java @@ -25,7 +25,6 @@ import javax.xml.stream.XMLStreamReader; import javax.xml.validation.SchemaFactory; import java.io.File; -import java.io.IOException; import java.io.InputStream; /* Parses an XML of this kind (see below). Also see @GoPluginDescriptorParser and gocd-bundle-descriptor.xsd. @@ -83,14 +82,14 @@ private GoPluginBundleDescriptorParser() { } public static GoPluginBundleDescriptor parseXML(InputStream pluginXml, - BundleOrPluginFileDetails bundleOrPluginJarFile) throws IOException, JAXBException, XMLStreamException, SAXException { + BundleOrPluginFileDetails bundleOrPluginJarFile) throws JAXBException, XMLStreamException, SAXException { return parseXML(pluginXml, bundleOrPluginJarFile.file().getAbsolutePath(), bundleOrPluginJarFile.extractionLocation(), bundleOrPluginJarFile.isBundledPlugin()); } static GoPluginBundleDescriptor parseXML(InputStream pluginXML, String pluginJarFileLocation, File pluginBundleLocation, - boolean isBundledPlugin) throws IOException, JAXBException, XMLStreamException, SAXException { + boolean isBundledPlugin) throws JAXBException, XMLStreamException, SAXException { GoPluginBundleDescriptor bundle = deserializeXML(pluginXML, GoPluginBundleDescriptor.class); bundle.pluginDescriptors().forEach(d -> { diff --git a/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParser.java b/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParser.java index 59c1bd049eeb..eb8b5943bfd8 100644 --- a/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParser.java +++ b/plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParser.java @@ -25,7 +25,6 @@ import javax.xml.stream.XMLStreamReader; import javax.xml.validation.SchemaFactory; import java.io.File; -import java.io.IOException; import java.io.InputStream; public final class GoPluginDescriptorParser { @@ -53,14 +52,14 @@ private GoPluginDescriptorParser() { } public static GoPluginBundleDescriptor parseXML(InputStream pluginXml, - BundleOrPluginFileDetails bundleOrPluginJarFile) throws IOException, JAXBException, XMLStreamException, SAXException { + BundleOrPluginFileDetails bundleOrPluginJarFile) throws JAXBException, XMLStreamException, SAXException { return parseXML(pluginXml, bundleOrPluginJarFile.file().getAbsolutePath(), bundleOrPluginJarFile.extractionLocation(), bundleOrPluginJarFile.isBundledPlugin()); } static GoPluginBundleDescriptor parseXML(InputStream pluginXML, String pluginJarFileLocation, File pluginBundleLocation, - boolean isBundledPlugin) throws IOException, JAXBException, XMLStreamException, SAXException { + boolean isBundledPlugin) throws JAXBException, XMLStreamException, SAXException { GoPluginDescriptor plugin = deserializeXML(pluginXML, GoPluginDescriptor.class); plugin.pluginJarFileLocation(pluginJarFileLocation); plugin.bundleLocation(pluginBundleLocation); diff --git a/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/activation/DefaultGoPluginActivatorIntegrationTest.java b/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/activation/DefaultGoPluginActivatorIntegrationTest.java index a54cfd90ba66..9c5a9c8fc643 100644 --- a/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/activation/DefaultGoPluginActivatorIntegrationTest.java +++ b/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/activation/DefaultGoPluginActivatorIntegrationTest.java @@ -31,7 +31,6 @@ import com.thoughtworks.go.util.ZipUtil; import lib.test.DummyTestPluginInLibDirectory; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.apache.felix.framework.util.FelixConstants; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -46,7 +45,10 @@ import java.io.File; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; import java.util.zip.ZipInputStream; import static org.assertj.core.api.Assertions.assertThat; @@ -381,10 +383,9 @@ private File createBundleWithActivator(String destinationDir, Class... classe for (Class aClass : classesToBeAdded) { bundleBeingBuilt.add(aClass, InnerClassStrategy.NONE); } - ZipInputStream src = new ZipInputStream(bundleBeingBuilt.build()); - File bundleExplodedDir = explodeBundleIntoDirectory(src, destinationDir); - IOUtils.closeQuietly(src); - return bundleExplodedDir; + try (ZipInputStream src = new ZipInputStream(bundleBeingBuilt.build())) { + return explodeBundleIntoDirectory(src, destinationDir); + } } private File explodeBundleIntoDirectory(ZipInputStream src, String destinationDir) throws IOException { diff --git a/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/monitor/AbstractDefaultPluginJarLocationMonitorTest.java b/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/monitor/AbstractDefaultPluginJarLocationMonitorTest.java index 521dda32991e..914e0c52a739 100644 --- a/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/monitor/AbstractDefaultPluginJarLocationMonitorTest.java +++ b/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/monitor/AbstractDefaultPluginJarLocationMonitorTest.java @@ -17,16 +17,14 @@ import com.thoughtworks.go.plugin.FileHelper; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; -import java.nio.charset.Charset; +import java.nio.file.Files; abstract class AbstractDefaultPluginJarLocationMonitorTest { private static final int NO_OF_TRIES_TO_CHECK_MONITOR_RUN = 150; @@ -65,8 +63,8 @@ void copyPluginToThePluginDirectory(File pluginDir, } void updateFileContents(File someFile) { - try (FileOutputStream output = new FileOutputStream(someFile)) { - IOUtils.write("some rubbish", output, Charset.defaultCharset()); + try { + Files.writeString(someFile.toPath(), "some rubbish"); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParserTest.java b/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParserTest.java index f519ebbae2e4..4b299381aa4e 100644 --- a/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParserTest.java +++ b/plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/plugininfo/GoPluginDescriptorParserTest.java @@ -16,21 +16,21 @@ package com.thoughtworks.go.plugin.infra.plugininfo; import jakarta.xml.bind.JAXBException; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.util.List; import static java.lang.String.format; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.*; class GoPluginDescriptorParserTest { @Test void shouldPerformPluginXsdValidationAndFailWhenIDIsNotPresent() { - InputStream pluginXml = IOUtils.toInputStream("", StandardCharsets.UTF_8); + InputStream pluginXml = new ByteArrayInputStream("".getBytes(UTF_8)); final JAXBException e = assertThrows(JAXBException.class, () -> GoPluginDescriptorParser.parseXML(pluginXml, "/tmp/", new File("/tmp/"), true)); assertTrue(e.getCause().getMessage().contains("Attribute 'id' must appear on element 'go-plugin'"), format("Message not correct: [%s]", e.getCause().getMessage())); @@ -38,7 +38,7 @@ void shouldPerformPluginXsdValidationAndFailWhenIDIsNotPresent() { @Test void shouldPerformPluginXsdValidationAndFailWhenVersionIsNotPresent() { - InputStream pluginXml = IOUtils.toInputStream("", StandardCharsets.UTF_8); + InputStream pluginXml = new ByteArrayInputStream("".getBytes(UTF_8)); final JAXBException e = assertThrows(JAXBException.class, () -> GoPluginDescriptorParser.parseXML(pluginXml, "/tmp/", new File("/tmp/"), true)); assertTrue(e.getCause().getMessage().contains("Attribute 'version' must appear on element 'go-plugin'"), format("Message not correct: [%s]", e.getCause().getMessage())); @@ -46,7 +46,7 @@ void shouldPerformPluginXsdValidationAndFailWhenVersionIsNotPresent() { @Test void shouldValidatePluginVersion() { - InputStream pluginXml = IOUtils.toInputStream("", StandardCharsets.UTF_8); + InputStream pluginXml = new ByteArrayInputStream("".getBytes(UTF_8)); final JAXBException e = assertThrows(JAXBException.class, () -> GoPluginDescriptorParser.parseXML(pluginXml, "/tmp/", new File("/tmp/"), true)); assertTrue(e.getCause().getMessage().contains("Value '10' of attribute 'version' of element 'go-plugin' is not valid"), format("Message not correct: [%s]", e.getCause().getMessage())); diff --git a/server/src/main/java/com/thoughtworks/go/server/controller/AgentRegistrationController.java b/server/src/main/java/com/thoughtworks/go/server/controller/AgentRegistrationController.java index 5137976b5e37..2b0b7a0e395c 100644 --- a/server/src/main/java/com/thoughtworks/go/server/controller/AgentRegistrationController.java +++ b/server/src/main/java/com/thoughtworks/go/server/controller/AgentRegistrationController.java @@ -43,11 +43,11 @@ import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.util.Base64; import java.util.List; import static com.thoughtworks.go.util.SystemEnvironment.AGENT_EXTRA_PROPERTIES; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.commons.codec.binary.Base64.encodeBase64String; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.springframework.http.HttpStatus.*; @@ -213,7 +213,7 @@ public ResponseEntity agentRequest(@RequestParam("hostname") String host boolean isElasticAgent = elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId); try { - if (!encodeBase64String(hmac().doFinal(uuid.getBytes())).equals(token)) { + if (!Base64.getEncoder().encodeToString(hmac().doFinal(uuid.getBytes())).equals(token)) { String message = "Not a valid token."; LOG.error("Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]" + "ElasticAgentID=[{}] PluginID=[{}]", FORBIDDEN, message, uuid, hostname, elasticAgentId, elasticPluginId); @@ -324,7 +324,7 @@ public ResponseEntity getToken(@RequestParam("uuid") String uuid) { } String token; synchronized (HMAC_GENERATION_MUTEX) { - token = encodeBase64String(hmac().doFinal(uuid.getBytes())); + token = Base64.getEncoder().encodeToString(hmac().doFinal(uuid.getBytes())); } return new ResponseEntity<>(token, OK); @@ -342,8 +342,8 @@ private Agent createAgentFromRequest(String uuid, String hostname, String ip, St private String getAgentExtraProperties() { if (agentExtraProperties == null) { - String base64OfSystemProperty = encodeBase64String(systemEnvironment.get(AGENT_EXTRA_PROPERTIES).getBytes(UTF_8)); - String base64OfEmptyString = encodeBase64String("".getBytes(UTF_8)); + String base64OfSystemProperty = Base64.getEncoder().encodeToString(systemEnvironment.get(AGENT_EXTRA_PROPERTIES).getBytes(UTF_8)); + String base64OfEmptyString = Base64.getEncoder().encodeToString("".getBytes(UTF_8)); this.agentExtraProperties = base64OfSystemProperty.length() >= MAX_HEADER_LENGTH ? base64OfEmptyString : base64OfSystemProperty; } diff --git a/server/src/main/java/com/thoughtworks/go/server/controller/GoConfigAdministrationController.java b/server/src/main/java/com/thoughtworks/go/server/controller/GoConfigAdministrationController.java index 0432f3c4faaf..a2fbbec2a999 100644 --- a/server/src/main/java/com/thoughtworks/go/server/controller/GoConfigAdministrationController.java +++ b/server/src/main/java/com/thoughtworks/go/server/controller/GoConfigAdministrationController.java @@ -29,7 +29,6 @@ import com.thoughtworks.go.server.service.SecurityService; import com.thoughtworks.go.server.web.JsonView; import com.thoughtworks.go.util.SystemEnvironment; -import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -75,7 +74,7 @@ public void getConfigRevision(@RequestParam(value = "version", required = true) response.setCharacterEncoding("utf-8"); response.setHeader(X_CRUISE_CONFIG_MD5, md5); if (configRevision.isByteArrayBacked()) { - IOUtils.write(configRevision.getConfigXmlBytes(), response.getOutputStream()); + response.getOutputStream().write(configRevision.getConfigXmlBytes()); } else { response.getWriter().write(configRevision.getContent()); } diff --git a/server/src/main/java/com/thoughtworks/go/server/newsecurity/filters/AgentAuthenticationFilter.java b/server/src/main/java/com/thoughtworks/go/server/newsecurity/filters/AgentAuthenticationFilter.java index aef30928521b..5cfa869e625c 100644 --- a/server/src/main/java/com/thoughtworks/go/server/newsecurity/filters/AgentAuthenticationFilter.java +++ b/server/src/main/java/com/thoughtworks/go/server/newsecurity/filters/AgentAuthenticationFilter.java @@ -38,8 +38,8 @@ import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; +import java.util.Base64; -import static org.apache.commons.codec.binary.Base64.encodeBase64String; import static org.apache.commons.lang3.StringUtils.isBlank; @Component @@ -106,7 +106,7 @@ private void tokenBasedFilter(HttpServletRequest request, HttpServletResponse re /*Fixes:#8427 HMAC generation is not thread safe, if multiple agents try to authenticate at the same time the hmac generated using the Agent UUID would not match the actual token.*/ synchronized String hmacOf(String string) { - return encodeBase64String(hmac().doFinal(string.getBytes())); + return Base64.getEncoder().encodeToString(hmac().doFinal(string.getBytes())); } private boolean isAuthenticated(AgentToken agentToken, AuthenticationToken authenticationToken) { diff --git a/server/src/main/java/com/thoughtworks/go/server/service/BackupService.java b/server/src/main/java/com/thoughtworks/go/server/service/BackupService.java index ca6f73dca7de..0085bd491f83 100644 --- a/server/src/main/java/com/thoughtworks/go/server/service/BackupService.java +++ b/server/src/main/java/com/thoughtworks/go/server/service/BackupService.java @@ -38,15 +38,16 @@ import com.thoughtworks.go.util.VoidThrowingFn; import org.apache.commons.io.DirectoryWalker; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.codec.Hex; import org.springframework.stereotype.Service; import java.io.*; +import java.nio.CharBuffer; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -316,15 +317,18 @@ private void backupConfig(File backupDir, List backupUpdat new DirectoryStructureWalker(configDirectory, configZip, cruiseConfigFile, desCipherFile, aesCipherFile).walk(); configZip.putNextEntry(new ZipEntry(cruiseConfigFile.getName())); - IOUtils.write(goConfigService.xml(), configZip, UTF_8); + String xml = goConfigService.xml(); + if (xml != null) { + configZip.write(xml.getBytes(UTF_8)); + } if (desCipherFile.exists()) { configZip.putNextEntry(new ZipEntry(desCipherFile.getName())); - IOUtils.write(encodeHexString(new DESCipherProvider(systemEnvironment).getKey()), configZip, UTF_8); + configZip.write(encodeHexString(new DESCipherProvider(systemEnvironment).getKey()).getBytes(UTF_8)); } configZip.putNextEntry(new ZipEntry(aesCipherFile.getName())); - IOUtils.write(encodeHexString(new AESCipherProvider(systemEnvironment).getKey()), configZip, UTF_8); + configZip.write(encodeHexString(new AESCipherProvider(systemEnvironment).getKey()).getBytes(UTF_8)); } } diff --git a/server/src/main/java/com/thoughtworks/go/server/service/builders/AntTaskBuilder.java b/server/src/main/java/com/thoughtworks/go/server/service/builders/AntTaskBuilder.java index e49654bd1137..d21374407089 100644 --- a/server/src/main/java/com/thoughtworks/go/server/service/builders/AntTaskBuilder.java +++ b/server/src/main/java/com/thoughtworks/go/server/service/builders/AntTaskBuilder.java @@ -15,21 +15,20 @@ */ package com.thoughtworks.go.server.service.builders; -import java.io.File; - import com.thoughtworks.go.config.AntTask; +import com.thoughtworks.go.domain.Pipeline; import com.thoughtworks.go.domain.builder.Builder; import com.thoughtworks.go.domain.builder.CommandBuilder; -import com.thoughtworks.go.domain.Pipeline; import com.thoughtworks.go.server.service.UpstreamPipelineResolver; -import com.thoughtworks.go.util.FileUtil; import org.springframework.stereotype.Component; +import java.io.File; + @Component public class AntTaskBuilder implements TaskBuilder { @Override public Builder createBuilder(BuilderFactory builderFactory, AntTask task, Pipeline pipeline, UpstreamPipelineResolver resolver) { - String newWorkingDir = FileUtil.join(pipeline.defaultWorkingFolder(), task.workingDirectory()); + String newWorkingDir = TaskBuilder.join(pipeline.defaultWorkingFolder(), task.workingDirectory()); String argument = task.arguments(); Builder cancelBuilder = builderFactory.builderFor(task.cancelTask(), pipeline, resolver); diff --git a/server/src/main/java/com/thoughtworks/go/server/service/builders/NantTaskBuilder.java b/server/src/main/java/com/thoughtworks/go/server/service/builders/NantTaskBuilder.java index b7f67f476b76..86c5a86ce9af 100644 --- a/server/src/main/java/com/thoughtworks/go/server/service/builders/NantTaskBuilder.java +++ b/server/src/main/java/com/thoughtworks/go/server/service/builders/NantTaskBuilder.java @@ -15,21 +15,20 @@ */ package com.thoughtworks.go.server.service.builders; -import java.io.File; - import com.thoughtworks.go.config.NantTask; +import com.thoughtworks.go.domain.Pipeline; import com.thoughtworks.go.domain.builder.Builder; import com.thoughtworks.go.domain.builder.CommandBuilder; -import com.thoughtworks.go.domain.Pipeline; import com.thoughtworks.go.server.service.UpstreamPipelineResolver; -import com.thoughtworks.go.util.FileUtil; import org.springframework.stereotype.Component; +import java.io.File; + @Component public class NantTaskBuilder implements TaskBuilder { @Override public Builder createBuilder(BuilderFactory builderFactory, NantTask task, Pipeline pipeline, UpstreamPipelineResolver resolver) { - File taskWorkingDirectory = new File(FileUtil.join(pipeline.defaultWorkingFolder(), task.workingDirectory())); + File taskWorkingDirectory = new File(TaskBuilder.join(pipeline.defaultWorkingFolder(), task.workingDirectory())); String command = task.command(); String argument = task.arguments(); Builder cancelBuilder = builderFactory.builderFor(task.cancelTask(), pipeline, resolver); diff --git a/server/src/main/java/com/thoughtworks/go/server/service/builders/RakeTaskBuilder.java b/server/src/main/java/com/thoughtworks/go/server/service/builders/RakeTaskBuilder.java index c88b292de2fa..42fc2cdcb61e 100644 --- a/server/src/main/java/com/thoughtworks/go/server/service/builders/RakeTaskBuilder.java +++ b/server/src/main/java/com/thoughtworks/go/server/service/builders/RakeTaskBuilder.java @@ -22,14 +22,13 @@ import com.thoughtworks.go.domain.builder.CommandBuilder; import com.thoughtworks.go.domain.Pipeline; import com.thoughtworks.go.server.service.UpstreamPipelineResolver; -import com.thoughtworks.go.util.FileUtil; import org.springframework.stereotype.Component; @Component public class RakeTaskBuilder implements TaskBuilder { @Override public Builder createBuilder(BuilderFactory builderFactory, RakeTask task, Pipeline pipeline, UpstreamPipelineResolver resolver) { - String newWorkingDir = FileUtil.join(pipeline.defaultWorkingFolder(), task.workingDirectory()); + String newWorkingDir = TaskBuilder.join(pipeline.defaultWorkingFolder(), task.workingDirectory()); String argument = task.arguments(); Builder builder = builderFactory.builderFor(task.cancelTask(), pipeline, resolver); return new CommandBuilder("rake", argument, new File(newWorkingDir), task.getConditions(), builder, task.describe()); diff --git a/server/src/main/java/com/thoughtworks/go/server/service/builders/TaskBuilder.java b/server/src/main/java/com/thoughtworks/go/server/service/builders/TaskBuilder.java index 01f837d9a999..da9b0b226803 100644 --- a/server/src/main/java/com/thoughtworks/go/server/service/builders/TaskBuilder.java +++ b/server/src/main/java/com/thoughtworks/go/server/service/builders/TaskBuilder.java @@ -19,7 +19,18 @@ import com.thoughtworks.go.domain.Pipeline; import com.thoughtworks.go.domain.Task; import com.thoughtworks.go.server.service.UpstreamPipelineResolver; +import com.thoughtworks.go.util.FileUtil; +import org.apache.commons.io.FilenameUtils; + +import java.io.File; public interface TaskBuilder { Builder createBuilder(BuilderFactory builderFactory, T task, Pipeline pipeline, UpstreamPipelineResolver resolver); + + static String join(File defaultWorkingDir, String actualFileToUse) { + if (actualFileToUse == null) { + return FilenameUtils.separatorsToUnix(defaultWorkingDir.getPath()); + } + return FileUtil.applyBaseDirIfRelativeAndNormalize(defaultWorkingDir, new File(actualFileToUse)); + } } diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/GoServerTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/GoServerTest.java index 015e7dcfedc9..9b82914ad26d 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/GoServerTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/GoServerTest.java @@ -17,7 +17,6 @@ import com.thoughtworks.go.util.SubprocessLogger; import com.thoughtworks.go.util.SystemEnvironment; -import com.thoughtworks.go.util.TestFileUtil; import com.thoughtworks.go.util.validators.Validation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,6 +26,7 @@ import uk.org.webcompere.systemstubs.properties.SystemProperties; import java.io.File; +import java.nio.file.Files; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -51,7 +51,7 @@ public void shouldValidateOnServerStartup() throws Exception { final SystemEnvironment systemEnvironment = mock(SystemEnvironment.class); StubGoServer goServer = new StubGoServer(systemEnvironment, Validation.SUCCESS); goServer.subprocessLogger = mock(SubprocessLogger.class); - final File tmpFile = TestFileUtil.createTempFile("keystore.tmp"); + final File tmpFile = Files.createTempFile("keystore", ".tmp").toFile(); tmpFile.deleteOnExit(); diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerTest.java index b4a396040a99..d6a23bce47df 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerTest.java @@ -27,7 +27,6 @@ import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -46,7 +45,6 @@ import java.nio.file.Path; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; -import java.util.Arrays; import java.util.Base64; import static com.thoughtworks.go.util.SystemEnvironment.AGENT_EXTRA_PROPERTIES; @@ -54,7 +52,8 @@ import static java.util.Base64.getEncoder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import static org.springframework.http.HttpStatus.CONFLICT; @@ -67,7 +66,6 @@ public class AgentRegistrationControllerTest { private AgentRegistrationController controller; private SystemEnvironment systemEnvironment; private PluginsZip pluginsZip; - private File pluginZipFile; private EphemeralAutoRegisterKeyService ephemeralAutoRegisterKeyService; @BeforeEach @@ -76,7 +74,7 @@ public void setUp(@TempDir Path temporaryFolder) throws Exception { systemEnvironment = mock(SystemEnvironment.class); goConfigService = mock(GoConfigService.class); ephemeralAutoRegisterKeyService = mock(EphemeralAutoRegisterKeyService.class); - pluginZipFile = Files.createFile(temporaryFolder.resolve("plugins.zip")).toFile(); + File pluginZipFile = Files.createFile(temporaryFolder.resolve("plugins.zip")).toFile(); FileUtils.writeStringToFile(pluginZipFile, "content", UTF_8); when(systemEnvironment.get(SystemEnvironment.ALL_PLUGINS_ZIP_PATH)).thenReturn(pluginZipFile.getAbsolutePath()); when(systemEnvironment.get(AGENT_EXTRA_PROPERTIES)).thenReturn(""); @@ -206,7 +204,7 @@ public void contentShouldIncludeMd5Checksum_forAgent() throws Exception { assertEquals(DigestUtils.md5Hex(stream), response.getHeader("Content-MD5")); } try (InputStream is = JarDetector.createFromRelativeDefaultFile(systemEnvironment, "agent.jar").invoke()) { - assertTrue(Arrays.equals(IOUtils.toByteArray(is), response.getContentAsByteArray())); + assertArrayEquals(is.readAllBytes(), response.getContentAsByteArray()); } } @@ -244,7 +242,7 @@ public void contentShouldIncludeMd5Checksum_forAgentLauncher() throws Exception assertEquals(DigestUtils.md5Hex(stream), response.getHeader("Content-MD5")); } try (InputStream is = JarDetector.createFromRelativeDefaultFile(systemEnvironment, "agent-launcher.jar").invoke()) { - assertTrue(Arrays.equals(IOUtils.toByteArray(is), response.getContentAsByteArray())); + assertArrayEquals(is.readAllBytes(), response.getContentAsByteArray()); } } @@ -285,7 +283,7 @@ public void shouldRenderTheTfsJar() throws Exception { assertEquals(DigestUtils.md5Hex(stream), response.getHeader("Content-MD5")); } try (InputStream is = JarDetector.tfsJar(systemEnvironment).getJarURL().openStream()) { - assertTrue(Arrays.equals(IOUtils.toByteArray(is), response.getContentAsByteArray())); + assertArrayEquals(is.readAllBytes(), response.getContentAsByteArray()); } } @@ -296,7 +294,7 @@ public void shouldGenerateToken() { when(agentService.findAgent("uuid-from-agent")).thenReturn(AgentInstanceMother.idle()); when(agentService.isRegistered("uuid-from-agent")).thenReturn(false); - final ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); + ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody(), is("JCmJaW6YbEA4fIUqf8L9lRV81ua10wV+wRYOFdaBLcM=")); @@ -309,7 +307,7 @@ public void shouldRejectGenerateTokenRequestIfAgentIsInPendingState() { when(agentService.findAgent("uuid-from-agent")).thenReturn(AgentInstanceMother.pendingInstance()); when(agentService.isRegistered("uuid-from-agent")).thenReturn(false); - final ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); + ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); assertThat(responseEntity.getBody(), is("A token has already been issued for this agent.")); @@ -322,7 +320,7 @@ public void shouldRejectGenerateTokenRequestIfAgentIsInConfig() { when(agentService.findAgent("uuid-from-agent")).thenReturn(AgentInstanceMother.idle()); when(agentService.isRegistered("uuid-from-agent")).thenReturn(true); - final ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); + ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); assertThat(responseEntity.getBody(), is("A token has already been issued for this agent.")); @@ -330,7 +328,7 @@ public void shouldRejectGenerateTokenRequestIfAgentIsInConfig() { @Test public void shouldRejectGenerateTokenRequestIfUUIDIsEmpty() { - final ResponseEntity responseEntity = controller.getToken(" "); + ResponseEntity responseEntity = controller.getToken(" "); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); assertThat(responseEntity.getBody(), is("UUID cannot be blank.")); @@ -343,7 +341,7 @@ public void shouldRejectRegistrationRequestWhenInvalidTokenProvided() { when(goConfigService.serverConfig()).thenReturn(serverConfig); when(agentService.createAgentUsername("blahAgent-uuid", request.getRemoteAddr(), "blahAgent-host")).thenReturn(new Username("some-agent-login-name")); - ResponseEntity responseEntity = controller.agentRequest("blahAgent-host", "blahAgent-uuid", "blah-location", "34567", "osx", "", "", "", "", "", "", "an-invalid-token", request); + ResponseEntity responseEntity = controller.agentRequest("blahAgent-host", "blahAgent-uuid", "blah-location", "34567", "osx", "", "", "", "", "", "", "an-invalid-token", request); assertThat(responseEntity.getBody(), is("Not a valid token.")); assertThat(responseEntity.getStatusCode(), is(HttpStatus.FORBIDDEN)); diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java index 7166d067d3b7..40aa9f8e19d7 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java @@ -23,7 +23,6 @@ import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor; import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -34,10 +33,12 @@ import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; +import java.util.Objects; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -163,8 +164,9 @@ public void onPluginMetadataLoad_shouldCopyPluginEndpointJsWhenCachingPluginStat assertTrue(pluginDirPath.toFile().exists()); assertTrue(actualPath.toFile().exists()); - byte[] expected = IOUtils.toByteArray(getClass().getResource("/plugin-endpoint.js")); - assertArrayEquals(expected, Files.readAllBytes(actualPath), "Content of plugin-endpoint.js should be preserved"); + try (InputStream is = getClass().getResourceAsStream("/plugin-endpoint.js")) { + assertArrayEquals(Objects.requireNonNull(is).readAllBytes(), Files.readAllBytes(actualPath), "Content of plugin-endpoint.js should be preserved"); + } } @Test @@ -239,7 +241,9 @@ public void onPluginMetadataLoad_shouldKnowPluginStaticAssetsPath() throws Excep } private String testDataZipArchive() throws IOException { - return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResource("/plugin_cache_test.zip")))); + try (InputStream is = getClass().getResourceAsStream("/plugin_cache_test.zip")) { + return new String(Base64.getEncoder().encode(Objects.requireNonNull(is).readAllBytes())); + } } private void addAnalyticsPluginInfoToStore(String pluginId) { diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/service/support/toggle/FeatureToggleRepositoryTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/service/support/toggle/FeatureToggleRepositoryTest.java index ef0f771b9a08..1378cc2da3b7 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/service/support/toggle/FeatureToggleRepositoryTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/service/support/toggle/FeatureToggleRepositoryTest.java @@ -20,7 +20,6 @@ import com.thoughtworks.go.server.domain.support.toggle.FeatureToggles; import com.thoughtworks.go.util.SystemEnvironment; import com.thoughtworks.go.util.TempDirUtils; -import com.thoughtworks.go.util.TestFileUtil; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterEach; @@ -114,9 +113,9 @@ public void shouldNotFailWhenSpecifiedUserTogglesFileIsNotFound() throws Excepti @Test public void shouldNotFailWhenContentOfUserTogglesFileIsInvalid() throws Exception { - File toggleFile = TestFileUtil.createTempFile("available.toggle.test"); - FileUtils.writeStringToFile(toggleFile, "SOME-INVALID-CONTENT", UTF_8); - setupUserToggleFileAs(toggleFile); + Path toggleFile = temporaryFolder.resolve("available.toggle.test"); + Files.writeString(toggleFile, "SOME-INVALID-CONTENT", UTF_8); + setupUserToggleFileAs(toggleFile.toFile()); FeatureToggleRepository repository = new FeatureToggleRepository(environment); diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/web/FileModelAndViewTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/web/FileModelAndViewTest.java index e8ac5a13cba8..6a48bdc9f47a 100644 --- a/server/src/test-fast/java/com/thoughtworks/go/server/web/FileModelAndViewTest.java +++ b/server/src/test-fast/java/com/thoughtworks/go/server/web/FileModelAndViewTest.java @@ -17,7 +17,6 @@ import com.thoughtworks.go.domain.FileHandler; import com.thoughtworks.go.server.domain.ZippedArtifact; -import com.thoughtworks.go.util.TestFileUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; @@ -25,9 +24,10 @@ import org.springframework.web.servlet.ModelAndView; import java.io.File; +import java.nio.file.Files; -import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; public class FileModelAndViewTest { private MockHttpServletResponse response; @@ -36,12 +36,12 @@ public class FileModelAndViewTest { @BeforeEach public void setUp() throws Exception { response = new MockHttpServletResponse(); - existFile = TestFileUtil.createTempFile("a.log"); - existFile.createNewFile(); + existFile = Files.createTempFile("a", ".log").toFile(); + existFile.deleteOnExit(); } @Test - public void shouldReturnFileViewWhenSha1IsEmpty() throws Exception { + public void shouldReturnFileViewWhenSha1IsEmpty() { FileModelAndView.createFileView(existFile, null); assertThat(response.getStatus(), is(200)); } @@ -54,26 +54,26 @@ public void shouldReturn304AsStatusCodeWhenSha1IsSameAsProvidedValue() throws Ex } @Test - public void shouldReturnModelWithZipFlagTurnedOnIfZipIsNeeded() throws Exception { + public void shouldReturnModelWithZipFlagTurnedOnIfZipIsNeeded() { ZippedArtifact zippedArtifact = new ZippedArtifact(existFile.getParentFile(), existFile.getName()); ModelAndView modelAndView = FileModelAndView.createFileView(zippedArtifact, ""); assertThat(modelAndView.getModel().containsKey(FileView.NEED_TO_ZIP), is(true)); } @Test - public void shouldReturnModelWithZipFlagTurnedOffIfZipIsNotNeeded() throws Exception { + public void shouldReturnModelWithZipFlagTurnedOffIfZipIsNotNeeded() { ModelAndView modelAndView = FileModelAndView.createFileView(existFile, ""); assertThat(modelAndView.getModel().containsKey(FileView.NEED_TO_ZIP), is(false)); } @Test - public void shouldReturnAnErrorMessageForConsoleLogNotFound() throws Exception { + public void shouldReturnAnErrorMessageForConsoleLogNotFound() { assertThat(((ResponseCodeView) FileModelAndView.fileNotFound("cruise-output/console.log").getView()).getContent(), is("Console log for this job is unavailable as it may have been purged by Go or " + "deleted externally.")); } @Test - public void shouldReturnAnErrorMessageForNormalFileNotFound() throws Exception { + public void shouldReturnAnErrorMessageForNormalFileNotFound() { assertThat(((ResponseCodeView) FileModelAndView.fileNotFound("bring/sally/up/bring/sally/down").getView()).getContent(), is("Artifact 'bring/sally/up/bring/sally/down' is unavailable as " + "it may have been purged by Go or deleted externally.")); } diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java index 1622e821cd83..fdb8e78834e3 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java @@ -61,7 +61,6 @@ import com.thoughtworks.go.util.command.CommandLine; import com.thoughtworks.go.util.command.ConsoleResult; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java index 997cfe01c4f3..61f267a2aadc 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java +++ b/server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java @@ -28,7 +28,6 @@ import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.util.GoConfigFileHelper; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/server/src/test-integration/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerIntegrationTest.java index 9f032c729768..87dfc500ef03 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/server/controller/AgentRegistrationControllerIntegrationTest.java @@ -89,7 +89,7 @@ public void shouldRegisterLocalAgent() { System.setProperty(AUTO_REGISTER_LOCAL_AGENT_ENABLED.propertyName(), "true"); String uuid = UUID.randomUUID().toString(); MockHttpServletRequest request = new MockHttpServletRequest(); - final ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); + ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); Agent agent = agentService.getAgentByUUID(uuid); assertThat(agent.getHostname(), is("hostname")); @@ -104,7 +104,7 @@ public void shouldRegisterElasticAgent() { String uuid = UUID.randomUUID().toString(); String elasticAgentId = UUID.randomUUID().toString(); MockHttpServletRequest request = new MockHttpServletRequest(); - final ResponseEntity responseEntity = controller.agentRequest("elastic-agent-hostname", + ResponseEntity responseEntity = controller.agentRequest("elastic-agent-hostname", uuid, "sandbox", "100", @@ -147,7 +147,7 @@ public void shouldNotRegisterElasticAgentWithDuplicateElasticAgentID() { Agent agent = agentService.getAgentByUUID(uuid); assertTrue(agent.isElastic()); - final ResponseEntity responseEntity = controller.agentRequest("elastic-agent-hostname", + ResponseEntity responseEntity = controller.agentRequest("elastic-agent-hostname", uuid, "sandbox", "100", @@ -170,7 +170,7 @@ public void shouldAddAgentInPendingState() { System.setProperty(AUTO_REGISTER_LOCAL_AGENT_ENABLED.propertyName(), "false"); String uuid = UUID.randomUUID().toString(); MockHttpServletRequest request = new MockHttpServletRequest(); - final ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); + ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); AgentInstance agentInstance = agentService.findAgent(uuid); assertTrue(agentInstance.isPending()); @@ -184,7 +184,7 @@ public void shouldAutoRegisterRemoteAgent() { System.setProperty(AUTO_REGISTER_LOCAL_AGENT_ENABLED.propertyName(), "false"); String uuid = UUID.randomUUID().toString(); MockHttpServletRequest request = new MockHttpServletRequest(); - final ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, goConfigService.serverConfig().getAgentAutoRegisterKey(), "", "", null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); + ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, goConfigService.serverConfig().getAgentAutoRegisterKey(), "", "", null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); AgentInstance agentInstance = agentService.findAgent(uuid); assertTrue(agentInstance.isIdle()); @@ -197,7 +197,7 @@ public void shouldAutoRegisterRemoteAgent() { public void shouldNotRegisterAgentWhenValidationFails() { MockHttpServletRequest request = new MockHttpServletRequest(); int totalAgentsBeforeRegistrationRequest = agentService.findRegisteredAgents().size(); - final ResponseEntity responseEntity = controller.agentRequest("hostname", "", "sandbox", "100", null, null, null, null, null, null, null, token("", goConfigService.serverConfig().getTokenGenerationKey()), request); + ResponseEntity responseEntity = controller.agentRequest("hostname", "", "sandbox", "100", null, null, null, null, null, null, null, token("", goConfigService.serverConfig().getTokenGenerationKey()), request); int totalAgentsAfterRegistrationRequest = agentService.findRegisteredAgents().size(); assertThat(totalAgentsBeforeRegistrationRequest, is(totalAgentsAfterRegistrationRequest)); @@ -209,7 +209,7 @@ public void shouldNotRegisterAgentWhenValidationFails() { public void shouldGenerateToken() { final String token = token("uuid-from-agent", goConfigService.serverConfig().getTokenGenerationKey()); - final ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); + ResponseEntity responseEntity = controller.getToken("uuid-from-agent"); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(responseEntity.getBody(), is(token)); @@ -224,7 +224,7 @@ public void shouldRejectGenerateTokenRequestIfAgentIsInPendingState() { final AgentInstance agentInstance = agentService.findAgent(uuid); assertTrue(agentInstance.isPending()); - final ResponseEntity responseEntity = controller.getToken(uuid); + ResponseEntity responseEntity = controller.getToken(uuid); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); assertThat(responseEntity.getBody(), is("A token has already been issued for this agent.")); @@ -237,7 +237,7 @@ public void shouldRejectGenerateTokenRequestIfAgentIsInConfig() { agentService.saveOrUpdate(new Agent(uuid, "hostname", "127.0.01", uuidGenerator.randomUuid())); assertTrue(agentService.findAgent(uuid).getAgentConfigStatus().equals(AgentConfigStatus.Enabled)); - final ResponseEntity responseEntity = controller.getToken(uuid); + ResponseEntity responseEntity = controller.getToken(uuid); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); assertThat(responseEntity.getBody(), is("A token has already been issued for this agent.")); @@ -245,7 +245,7 @@ public void shouldRejectGenerateTokenRequestIfAgentIsInConfig() { @Test public void shouldRejectGenerateTokenRequestIfUUIDIsEmpty() { - final ResponseEntity responseEntity = controller.getToken(" "); + ResponseEntity responseEntity = controller.getToken(" "); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); assertThat(responseEntity.getBody(), is("UUID cannot be blank.")); @@ -255,7 +255,7 @@ public void shouldRejectGenerateTokenRequestIfUUIDIsEmpty() { public void shouldRejectAgentRegistrationRequestWhenTokenIsInvalid() { String uuid = UUID.randomUUID().toString(); MockHttpServletRequest request = new MockHttpServletRequest(); - final ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, "invalid-token", request); + ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, "invalid-token", request); AgentInstance agentInstance = agentService.findAgent(uuid); @@ -271,7 +271,7 @@ public void shouldReIssueCertificateIfRegisteredAgentAsksForRegistrationWithoutA assertTrue(agentService.findAgent(uuid).getAgentConfigStatus().equals(AgentConfigStatus.Enabled)); MockHttpServletRequest request = new MockHttpServletRequest(); - final ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); + ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, null, null, null, null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); AgentInstance agentInstance = agentService.findAgent(uuid); @@ -287,7 +287,7 @@ public void shouldReIssueCertificateIfRegisteredAgentAsksForRegistrationWithAuto assertTrue(agentService.findAgent(uuid).getAgentConfigStatus().equals(AgentConfigStatus.Enabled)); MockHttpServletRequest request = new MockHttpServletRequest(); - final ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, goConfigService.serverConfig().getAgentAutoRegisterKey(), "", "", null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); + ResponseEntity responseEntity = controller.agentRequest("hostname", uuid, "sandbox", "100", null, goConfigService.serverConfig().getAgentAutoRegisterKey(), "", "", null, null, null, token(uuid, goConfigService.serverConfig().getTokenGenerationKey()), request); AgentInstance agentInstance = agentService.findAgent(uuid); diff --git a/server/src/test-integration/java/com/thoughtworks/go/server/controller/ArtifactsControllerIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/server/controller/ArtifactsControllerIntegrationTest.java index 2fe5a7277da4..588dc8934420 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/server/controller/ArtifactsControllerIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/server/controller/ArtifactsControllerIntegrationTest.java @@ -23,7 +23,7 @@ import com.thoughtworks.go.server.service.ConsoleService; import com.thoughtworks.go.server.web.ResponseCodeView; import com.thoughtworks.go.util.GoConfigFileHelper; -import com.thoughtworks.go.util.TestFileUtil; +import com.thoughtworks.go.util.TempFiles; import com.thoughtworks.go.util.ZipUtil; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; @@ -635,7 +635,8 @@ private void prepareTempConsoleOut(JobIdentifier jobIdentifier, String content) private ModelAndView postZipFolderFromTmp(File root, String folder) throws Exception { File source = file(root, "/tmp" + folder); - File zippedFile = zipUtil.zip(source, TestFileUtil.createUniqueTempFile(source.getName()), + String prefix = source.getName(); + File zippedFile = zipUtil.zip(source, TempFiles.createUniqueFile(prefix), Deflater.NO_COMPRESSION); zippedFile.deleteOnExit(); return postFile("", "zipfile", new FileInputStream(zippedFile), response); diff --git a/server/src/test-integration/java/com/thoughtworks/go/server/service/BackupServiceIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/server/service/BackupServiceIntegrationTest.java index 1ee0060e82fd..c63e31dba94b 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/server/service/BackupServiceIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/server/service/BackupServiceIntegrationTest.java @@ -38,7 +38,6 @@ import com.thoughtworks.go.util.command.InMemoryStreamConsumer; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.NameFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.joda.time.DateTime; diff --git a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java index 97358ee4a490..7a33e507eb0e 100644 --- a/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java +++ b/server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java @@ -28,7 +28,6 @@ import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult; import com.thoughtworks.go.util.GoConfigFileHelper; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/server/src/test-shared/java/com/thoughtworks/go/util/GoConfigFileHelper.java b/server/src/test-shared/java/com/thoughtworks/go/util/GoConfigFileHelper.java index f3dca3dadfc3..fb8c247d63f4 100644 --- a/server/src/test-shared/java/com/thoughtworks/go/util/GoConfigFileHelper.java +++ b/server/src/test-shared/java/com/thoughtworks/go/util/GoConfigFileHelper.java @@ -45,6 +45,8 @@ import java.io.File; import java.io.IOException; import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.UUID; @@ -84,9 +86,9 @@ private GoConfigFileHelper(String xml, GoConfigDao goConfigDao) { this.originalXml = xml; assignFileDao(goConfigDao); try { - File dir = TestFileUtil.createTempFolder("server-config-dir"); - this.configFile = new File(dir, "cruise-config.xml"); - configFile.deleteOnExit(); + Path dir = Files.createTempDirectory( "server-config-dir"); + this.configFile = new File(dir.toFile(), "cruise-config.xml"); + dir.toFile().deleteOnExit(); sysEnv = new SystemEnvironment(); sysEnv.setProperty(SystemEnvironment.CONFIG_FILE_PROPERTY, configFile.getAbsolutePath()); initializeConfigFile(); @@ -1025,7 +1027,7 @@ private MaterialConfigs invalidRepositoryMaterialConfigs() { } private File addPasswordFile() throws IOException { - passwordFile = TestFileUtil.createTempFile("password.properties"); + passwordFile = Files.createTempFile("password", ".properties").toFile(); passwordFile.deleteOnExit(); final String nonAdmin = "jez=ThmbShxAtJepX80c2JY1FzOEmUk=\n"; //in plain text: badger final String admin1 = "admin1=W6ph5Mm5Pz8GgiULbPgzG37mj9g=\n"; //in plain text: password @@ -1033,13 +1035,6 @@ private File addPasswordFile() throws IOException { return passwordFile; } - - /*public void addPipelineGroup(String groupName) { - CruiseConfig config = loadForEdit(); - config.addGroup(groupName); - writeConfigFile(config); - }*/ - private PipelineConfig addMaterialConfigForPipeline(String pipelinename, MaterialConfig... materialConfigs) { CruiseConfig cruiseConfig = loadForEdit(); PipelineConfig pipelineConfig = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString(pipelinename)); diff --git a/test/test-utils/src/main/java/com/thoughtworks/go/util/TempDirUtils.java b/test/test-utils/src/main/java/com/thoughtworks/go/util/TempDirUtils.java index 5962889fb98e..91b26f9dd754 100644 --- a/test/test-utils/src/main/java/com/thoughtworks/go/util/TempDirUtils.java +++ b/test/test-utils/src/main/java/com/thoughtworks/go/util/TempDirUtils.java @@ -29,7 +29,6 @@ public class TempDirUtils { private TempDirUtils() { } - public static Path createTempDirectoryIn(Path tempDir, String folderName) throws IOException { return isBlank(folderName) ? Files.createTempDirectory(tempDir, DIR_PREFIX) : Files.createDirectories(tempDir.resolve(folderName)); } @@ -48,6 +47,4 @@ public static File newFile(File file) throws IOException { } return file; } - - } diff --git a/base/src/main/java/com/thoughtworks/go/util/TestFileUtil.java b/test/test-utils/src/main/java/com/thoughtworks/go/util/TestFileUtil.java similarity index 71% rename from base/src/main/java/com/thoughtworks/go/util/TestFileUtil.java rename to test/test-utils/src/main/java/com/thoughtworks/go/util/TestFileUtil.java index bcb74c8ad26d..6d5fdd933c53 100644 --- a/base/src/main/java/com/thoughtworks/go/util/TestFileUtil.java +++ b/test/test-utils/src/main/java/com/thoughtworks/go/util/TestFileUtil.java @@ -16,23 +16,8 @@ package com.thoughtworks.go.util; import java.io.File; -import java.io.IOException; public class TestFileUtil { - private static TempFiles tempFiles = new TempFiles(); - - public static File createTempFolder(String folderName) { - return tempFiles.mkdir(folderName); - } - - public static File createUniqueTempFile(String prefix) { - return tempFiles.createUniqueFile(prefix); - } - - public static File createTempFile(String fileName) throws IOException { - return tempFiles.createFile(fileName); - } - public static File createTestFile(File testFolder, String path) throws Exception { File subfile = new File(testFolder, path); subfile.createNewFile();