Repository: gocd/gocd
Issue: Unreleased Resource: Streams in business continuity ViewResolver

https://github.com/gocd/gocd/blob/86b555e57daccec6b53b246f0dcdd4d0090566ef/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java#L40

The program can potentially fail to release a system resource.

Changed files:
server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java
plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoDocumentMother.java
server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java
base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java
server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java
server/src/test-integration/java/com/thoughtworks/go/config/FullConfigSaveFlowTestBase.java
server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineConfigsServiceIntegrationTest.java
plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java
config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java
common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java
config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlLoaderTest.java
server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java
server/src/test-integration/java/com/thoughtworks/go/config/CachedGoConfigIntegrationTest.java
server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsServiceTest.java
server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java

diff --git a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java
index d45bf86971..edd169b2c2 100644
--- a/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java
+++ b/base/src/main/java/com/thoughtworks/go/util/validators/FileValidator.java
@@ -21,6 +21,7 @@ import org.apache.commons.io.IOUtils;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.InputStream;
+import java.util.Objects;
 
 import static java.text.MessageFormat.format;
 
@@ -68,33 +69,20 @@ public class FileValidator implements Validator {
                 String message = format("File {0} is not readable or writeable.", file.getAbsolutePath());
                 return validation.addError(new RuntimeException(message));
             }
-        } else {
-            // Pull out the file from the class path
-            InputStream input = this.getClass().getResourceAsStream(srcDir + "/" + fileName);
+        }
+        // Pull out the file from the class path
+        try (InputStream input = this.getClass().getResourceAsStream(srcDir + "/" + fileName)) {
             if (input == null) {
                 String message = format("Resource {0}/{1} does not exist in the classpath", srcDir, fileName);
                 return validation.addError(new RuntimeException(message));
-            } else {
-                FileOutputStream output = null;
-                try {
-                    // Make sure the dir exists
-                    file.getParentFile().mkdirs();
-                    output = new FileOutputStream(file);
-                    IOUtils.copy(input, output);
-                } catch (Exception e) {
-                    return handleExceptionDuringFileHandling(validation, e);
-                } finally {
-                    try {
-                        input.close();
-                        if (output != null) {
-                            output.flush();
-                            output.close();
-                        }
-                    } catch (Exception e) {
-                        return handleExceptionDuringFileHandling(validation, e);
-                    }
-                }
             }
+            // Make sure the dir exists
+            file.getParentFile().mkdirs();
+            try (FileOutputStream output = new FileOutputStream(file)) {
+                IOUtils.copy(input, output);
+            }
+        } catch (Exception e) {
+            return handleExceptionDuringFileHandling(validation, e);
         }
         return Validation.SUCCESS;
     }
@@ -112,9 +100,9 @@ public class FileValidator implements Validator {
         FileValidator that = (FileValidator) o;
 
         if (shouldReplace != that.shouldReplace) return false;
-        if (fileName != null ? !fileName.equals(that.fileName) : that.fileName != null) return false;
-        if (srcDir != null ? !srcDir.equals(that.srcDir) : that.srcDir != null) return false;
-        return destDir != null ? destDir.equals(that.destDir) : that.destDir == null;
+        if (!Objects.equals(fileName, that.fileName)) return false;
+        if (!Objects.equals(srcDir, that.srcDir)) return false;
+        return Objects.equals(destDir, that.destDir);
     }
 
     @Override
diff --git a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java
index f49ae008d3..63b4aed02d 100644
--- a/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java
+++ b/common/src/test/java/com/thoughtworks/go/util/SvnLogXmlParserTest.java
@@ -23,7 +23,6 @@ import org.jdom2.input.SAXBuilder;
 import org.junit.jupiter.api.Test;
 
 import java.io.IOException;
-import java.io.InputStream;
 import java.text.ParseException;
 import java.util.HashMap;
 import java.util.List;
@@ -69,10 +68,7 @@ public class SvnLogXmlParserTest {
 
     @Test
     public void shouldParseSvnLogContainingNullComments() throws IOException {
-        String xml;
-        try (InputStream stream = getClass().getResourceAsStream("jemstep_svn_log.xml")) {
-            xml = IOUtils.toString(stream, UTF_8);
-        }
+        String xml = IOUtils.toString(getClass().getResource("jemstep_svn_log.xml"), UTF_8);
         SvnLogXmlParser parser = new SvnLogXmlParser();
         List<Modification> revisions = parser.parse(xml, "", new SAXBuilder());
 
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 807a0edd83..f504b22c22 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
@@ -35,7 +35,10 @@ import com.thoughtworks.go.config.remote.PartialConfig;
 import com.thoughtworks.go.config.rules.Allow;
 import com.thoughtworks.go.config.rules.Deny;
 import com.thoughtworks.go.config.rules.Rules;
-import com.thoughtworks.go.config.validation.*;
+import com.thoughtworks.go.config.validation.ArtifactDirValidator;
+import com.thoughtworks.go.config.validation.GoConfigValidator;
+import com.thoughtworks.go.config.validation.ServerIdImmutabilityValidator;
+import com.thoughtworks.go.config.validation.TokenGenerationKeyImmutabilityValidator;
 import com.thoughtworks.go.domain.*;
 import com.thoughtworks.go.domain.config.*;
 import com.thoughtworks.go.domain.label.PipelineLabel;
@@ -1690,15 +1693,6 @@ public class MagicalGoConfigXmlLoaderTest {
         ConfigMigrator.loadWithMigration(content); // should not fail with a validation exception
     }
 
-    @Test
-    void shouldLoadLargeConfigFileInReasonableTime() throws Exception {
-        String content = IOUtils.toString(getClass().getResourceAsStream("/data/big-cruise-config.xml"), UTF_8);
-//        long start = System.currentTimeMillis();
-        GoConfigHolder configHolder = ConfigMigrator.loadWithMigration(content);
-//        assertThat(System.currentTimeMillis() - start, lessThan(new Long(2000)));
-        assertThat(configHolder.config.schemaVersion()).isEqualTo(CONFIG_SCHEMA_VERSION);
-    }
-
     @Test
     void shouldLoadConfigWithPipelinesMatchingUpWithPipelineDefinitionCaseInsensitively() {
         String content = configWithEnvironments(
@@ -3884,7 +3878,7 @@ public class MagicalGoConfigXmlLoaderTest {
 
         final CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(configXml).configForEdit;
         final ArtifactTypeConfigs artifactTypeConfigs = cruiseConfig.pipelineConfigByName(
-                new CaseInsensitiveString("up42")).getStage("up42_stage")
+                        new CaseInsensitiveString("up42")).getStage("up42_stage")
                 .getJobs().getJob(new CaseInsensitiveString("up42_job")).artifactTypeConfigs();
 
         assertThat(artifactTypeConfigs).hasSize(1);
@@ -4224,7 +4218,7 @@ public class MagicalGoConfigXmlLoaderTest {
         ArtifactPluginInfo artifactPluginInfo = new ArtifactPluginInfo(pluginDescriptor, storeConfigSettings, publishArtifactSettings, fetchArtifactSettings, null, new Capabilities());
         ArtifactMetadataStore.instance().setPluginInfo(artifactPluginInfo);
 
-        String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+        String content = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
 
         CruiseConfig config = xmlLoader.loadConfigHolder(content).configForEdit;
         PipelineConfig ancestor = config.pipelineConfigByName(new CaseInsensitiveString("ancestor"));
@@ -4484,7 +4478,7 @@ public class MagicalGoConfigXmlLoaderTest {
         MaterialConfig materialConfig = config
                 .getPipelineConfigByName(new CaseInsensitiveString("pipeline"))
                 .materialConfigs().get(0);
-        
+
         assertThat(materialConfig).isInstanceOf(PluggableSCMMaterialConfig.class);
         assertThat(materialConfig.isInvertFilter()).isTrue();
     }
diff --git a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java
index de03835525..94a55028ba 100644
--- a/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java
+++ b/config/config-server/src/test/java/com/thoughtworks/go/config/MagicalGoConfigXmlWriterTest.java
@@ -55,14 +55,15 @@ import javax.xml.transform.stream.StreamSource;
 import javax.xml.validation.SchemaFactory;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
 
 import static com.thoughtworks.go.helper.MaterialConfigsMother.git;
 import static com.thoughtworks.go.helper.MaterialConfigsMother.tfs;
 import static com.thoughtworks.go.util.DataStructureUtils.m;
 import static com.thoughtworks.go.util.GoConstants.CONFIG_SCHEMA_VERSION;
 import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.hamcrest.Matchers.*;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
 import static org.junit.jupiter.api.Assertions.fail;
 
 @ExtendWith(ResetCipher.class)
@@ -321,7 +322,9 @@ public class MagicalGoConfigXmlWriterTest {
     @Test
     public void shouldBeAValidXSD() throws Exception {
         SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
-        factory.newSchema(new StreamSource(getClass().getResourceAsStream("/cruise-config.xsd")));
+        try (InputStream xsdStream = getClass().getResourceAsStream("/cruise-config.xsd")) {
+            factory.newSchema(new StreamSource(xsdStream));
+        }
     }
 
     @Test
diff --git a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java
index 6c96c73262..2ab651bece 100644
--- a/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java
+++ b/plugin-infra/go-plugin-access/src/main/java/com/thoughtworks/go/plugin/access/configrepo/ConfigRepoMigrator.java
@@ -40,9 +40,9 @@ public class ConfigRepoMigrator {
     }
 
     private Chainr getTransformerFor(int targetVersion) {
+        String targetVersionFile = String.format("/config-repo/migrations/%s.json", targetVersion);
         try {
-            String targetVersionFile = String.format("/config-repo/migrations/%s.json", targetVersion);
-            String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(targetVersionFile), StandardCharsets.UTF_8);
+            String transformJSON = IOUtils.toString(this.getClass().getResource(targetVersionFile), StandardCharsets.UTF_8);
             return Chainr.fromSpec(JsonUtils.jsonToList(transformJSON));
         } catch (Exception e) {
             throw new RuntimeException("Failed to migrate to version " + targetVersion, e);
@@ -50,9 +50,9 @@ public class ConfigRepoMigrator {
     }
 
     private Map<String, Object> getContextMap(int targetVersion) {
+        String contextFile = String.format("/config-repo/contexts/%s.json", targetVersion);
         try {
-            String contextFile = String.format("/config-repo/contexts/%s.json", targetVersion);
-            String contextJSON = IOUtils.toString(this.getClass().getResourceAsStream(contextFile), StandardCharsets.UTF_8);
+            String contextJSON = IOUtils.toString(this.getClass().getResource(contextFile), StandardCharsets.UTF_8);
             return JsonUtils.jsonToMap(contextJSON);
         } catch (Exception e) {
             LOGGER.debug(String.format("No context file present for target version '%s'.", targetVersion));
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 90885bd189..2cf16d1836 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
@@ -18,6 +18,7 @@ package com.thoughtworks.go.plugin.access.configrepo;
 import com.bazaarvoice.jolt.JsonUtils;
 import org.apache.commons.io.IOUtils;
 
+import java.nio.charset.StandardCharsets;
 import java.util.Map;
 
 import static com.bazaarvoice.jolt.utils.JoltUtils.remove;
@@ -41,7 +42,7 @@ class ConfigRepoDocumentMother {
 
     private Map<String, Object> getJSONFor(String fileName) {
         try {
-            String transformJSON = IOUtils.toString(this.getClass().getResourceAsStream(fileName), "UTF-8");
+            String transformJSON = IOUtils.toString(this.getClass().getResource(fileName), StandardCharsets.UTF_8);
             return JsonUtils.jsonToMap(transformJSON);
         } catch (Exception e) {
             throw new RuntimeException(e);
diff --git a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java
index 44c809ffd6..d16eaadece 100644
--- a/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java
+++ b/server/src/main/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolver.java
@@ -22,6 +22,7 @@ import org.springframework.stereotype.Component;
 
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
 import java.util.Map;
 
 import static java.lang.String.format;
@@ -36,9 +37,8 @@ public class ViewResolver {
     }
 
     public String resolveView(String viewName, Map<String, String> modelMap) {
-        try {
-            InputStream resourceAsStream = getResourceAsStream(viewName);
-            String template = IOUtils.toString(resourceAsStream, "UTF-8");
+        try (InputStream resourceAsStream = getResourceAsStream(viewName)) {
+            String template = IOUtils.toString(resourceAsStream, StandardCharsets.UTF_8);
             for (String modelKey : modelMap.keySet()) {
                 template = template.replaceAll(format("<<<%s>>>", modelKey), modelMap.get(modelKey));
             }
diff --git a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java
index b2ae2982cb..0a66781184 100644
--- a/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java
+++ b/server/src/main/java/com/thoughtworks/go/server/service/plugins/AnalyticsPluginAssetsService.java
@@ -118,7 +118,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin
 
         try {
             byte[] payload = Base64.getDecoder().decode(data.getBytes());
-            byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResourceAsStream("/" + PLUGIN_ENDPOINT_JS));
+            byte[] pluginEndpointJsContent = IOUtils.toByteArray(getClass().getResource("/" + PLUGIN_ENDPOINT_JS));
 
             try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(payload))) {
                 String assetsHash = calculateHash(payload, pluginEndpointJsContent);
@@ -139,7 +139,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin
 
     private void safeCopyExternalAssetsToPluginAssetRoot(final String pluginAssetsRoot) {
         Path externalAssetsPath = Paths.get(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS));
-        if (externalAssetsPath == null || !Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) {
+        if (!Files.exists(externalAssetsPath) || !Files.isDirectory(externalAssetsPath)) {
             LOGGER.debug("Analytics plugin external assets path ({}) does not exist or is not a directory. Not loading any assets.", externalAssetsPath);
             return;
         }
@@ -184,9 +184,7 @@ public class AnalyticsPluginAssetsService implements ServletContextAware, Plugin
         LOGGER.info("Deleting cached static assets for plugin: {}", pluginId);
         try {
             FileUtils.deleteDirectory(new File(pluginStaticAssetsRootDir(pluginId)));
-            if (pluginAssetPaths.containsKey(pluginId)) {
-                pluginAssetPaths.remove(pluginId);
-            }
+            pluginAssetPaths.remove(pluginId);
         } catch (Exception e) {
             LOGGER.error("Failed to delete cached static assets for plugin: {}", pluginId, e);
             ExceptionUtils.bomb(e);
diff --git a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java
index 4e750c430a..c71e9091a0 100644
--- a/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java
+++ b/server/src/test-fast/java/com/thoughtworks/go/addon/businesscontinuity/ViewResolverTest.java
@@ -3,6 +3,7 @@ package com.thoughtworks.go.addon.businesscontinuity;
 import org.apache.commons.io.IOUtils;
 import org.junit.jupiter.api.Test;
 
+import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 
 import static org.hamcrest.MatcherAssert.assertThat;
@@ -20,7 +21,7 @@ class ViewResolverTest {
         modelMap.put("key2", "value2");
 
         ViewResolver viewResolverSpy = spy(new ViewResolver());
-        doReturn(IOUtils.toInputStream(template)).when(viewResolverSpy).getResourceAsStream("sample");
+        doReturn(IOUtils.toInputStream(template, StandardCharsets.UTF_8)).when(viewResolverSpy).getResourceAsStream("sample");
         String resolvedView = viewResolverSpy.resolveView("sample", modelMap);
 
         assertThat(resolvedView, is("<html><head><link href=\\"value1\\\\value2\\"/></head></html>"));
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 283cdda954..52e4ce6b62 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
@@ -24,7 +24,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.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
@@ -35,7 +34,6 @@ import org.mockito.junit.jupiter.MockitoExtension;
 import javax.servlet.ServletContext;
 import java.io.File;
 import java.io.IOException;
-import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
@@ -76,7 +74,7 @@ public class AnalyticsPluginAssetsServiceTest {
     }
 
     @Test
-    public void shouldBeAPluginMetadataChangeListener() throws Exception {
+    public void shouldBeAPluginMetadataChangeListener() {
         verify(analyticsMetadataLoader).registerListeners(assetsService);
     }
 
@@ -165,7 +163,7 @@ public class AnalyticsPluginAssetsServiceTest {
 
         assertTrue(pluginDirPath.toFile().exists());
         assertTrue(actualPath.toFile().exists());
-        byte[] expected = IOUtils.toByteArray(getClass().getResourceAsStream("/plugin-endpoint.js"));
+        byte[] expected = IOUtils.toByteArray(getClass().getResource("/plugin-endpoint.js"));
         assertArrayEquals(expected, Files.readAllBytes(actualPath), "Content of plugin-endpoint.js should be preserved");
     }
 
@@ -178,8 +176,8 @@ public class AnalyticsPluginAssetsServiceTest {
         when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());
 
         when(systemEnvironment.get(SystemEnvironment.GO_ANALYTICS_PLUGIN_EXTERNAL_ASSETS)).thenReturn(externalAssetsDir.getAbsolutePath());
-        Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), "a.js"), "a".getBytes(StandardCharsets.UTF_8));
-        Files.write(Paths.get(externalAssetsDir.getAbsolutePath(), "b.js"), "b".getBytes(StandardCharsets.UTF_8));
+        Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), "a.js"), "a");
+        Files.writeString(Paths.get(externalAssetsDir.getAbsolutePath(), "b.js"), "b");
 
 
         assetsService.onPluginMetadataCreate(PLUGIN_ID);
@@ -241,7 +239,7 @@ public class AnalyticsPluginAssetsServiceTest {
     }
 
     private String testDataZipArchive() throws IOException {
-        return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResourceAsStream("/plugin_cache_test.zip"))));
+        return new String(Base64.getEncoder().encode(IOUtils.toByteArray(getClass().getResource("/plugin_cache_test.zip"))));
     }
 
     private void addAnalyticsPluginInfoToStore(String pluginId) {
diff --git a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java
index 6c83d9839b..ed7c1caab2 100644
--- a/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java
+++ b/server/src/test-fast/java/com/thoughtworks/go/server/web/BackupFilterTest.java
@@ -32,7 +32,6 @@ import javax.servlet.FilterChain;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
-import java.io.InputStream;
 import java.io.PrintWriter;
 import java.util.Optional;
 
@@ -48,7 +47,6 @@ public class BackupFilterTest {
     private FilterChain chain;
     private BackupService backupService;
     private PrintWriter writer;
-    private InputStream inputStream;
 
     @BeforeEach
     public void setUp() throws ServletException, IOException {
@@ -57,7 +55,6 @@ public class BackupFilterTest {
         res = mock(HttpServletResponse.class);
         backupService = mock(BackupService.class);
         chain = mock(FilterChain.class);
-        inputStream = BackupFilter.class.getClassLoader().getResourceAsStream("backup_in_progress.html");
         writer = mock(PrintWriter.class);
         when(res.getWriter()).thenReturn(writer);
         this.backupFilter = new BackupFilter(backupService);
@@ -99,7 +96,7 @@ public class BackupFilterTest {
         when(backupService.backupRunningSinceISO8601()).thenReturn(BACKUP_STARTED_AT);
         when(backupService.backupStartedBy()).thenReturn(BACKUP_STARTED_BY);
 
-        String content = IOUtils.toString(inputStream, UTF_8);
+        String content = IOUtils.toString(BackupFilter.class.getClassLoader().getResource("backup_in_progress.html"), UTF_8);
         content = backupFilter.replaceStringLiterals(content);
         Request request = request(HttpMethod.GET, "", "/go/agents");
 
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 e0a00b18b0..7417d7b1d6 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
@@ -54,7 +54,10 @@ import com.thoughtworks.go.serverhealth.HealthStateType;
 import com.thoughtworks.go.serverhealth.ServerHealthService;
 import com.thoughtworks.go.serverhealth.ServerHealthState;
 import com.thoughtworks.go.service.ConfigRepository;
-import com.thoughtworks.go.util.*;
+import com.thoughtworks.go.util.GoConstants;
+import com.thoughtworks.go.util.ReflectionUtil;
+import com.thoughtworks.go.util.SystemEnvironment;
+import com.thoughtworks.go.util.TempDirUtils;
 import com.thoughtworks.go.util.command.CommandLine;
 import com.thoughtworks.go.util.command.ConsoleResult;
 import org.apache.commons.io.FileUtils;
@@ -1200,7 +1203,7 @@ public class CachedGoConfigIntegrationTest {
         ArtifactStore artifactStore = new ArtifactStore("dockerhub", "cd.go.artifact.docker.registry");
         artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult());
         File configFile = new File(new SystemEnvironment().getCruiseConfigFile());
-        String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+        String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
         FileUtils.writeStringToFile(configFile, config, UTF_8);
 
         cachedGoConfig.forceReload();
@@ -1221,7 +1224,7 @@ public class CachedGoConfigIntegrationTest {
         ArtifactStore artifactStore = new ArtifactStore("dockerhub", "cd.go.artifact.docker.registry");
         artifactStoreService.create(Username.ANONYMOUS, artifactStore, new HttpLocalizedOperationResult());
         File configFile = new File(new SystemEnvironment().getCruiseConfigFile());
-        String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+        String config = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
         FileUtils.writeStringToFile(configFile, config, UTF_8);
 
         cachedGoConfig.forceReload();
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 2668a2a71e..32236b8585 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
@@ -41,8 +41,8 @@ import java.util.ArrayList;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 import static java.util.Arrays.asList;
-import static org.hamcrest.Matchers.*;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
 
 @ExtendWith(SpringExtension.class)
 @ContextConfiguration(locations = {
@@ -70,7 +70,7 @@ public abstract class FullConfigSaveFlowTestBase {
     public void setUp() throws Exception {
         configHelper = new GoConfigFileHelper(goConfigDao);
         configHelper.onSetUp();
-        xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/pluggable_artifacts_with_params.xml"), UTF_8));
+        xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/pluggable_artifacts_with_params.xml"), UTF_8));
         loader = new MagicalGoConfigXmlLoader(configCache, registry);
         setupMetadataForPlugin();
     }
diff --git a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java
index 6910f8d923..f9d8272ca5 100644
--- a/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java
+++ b/server/src/test-integration/java/com/thoughtworks/go/config/GoConfigMigrationIntegrationTest.java
@@ -27,7 +27,9 @@ import com.thoughtworks.go.security.ResetCipher;
 import com.thoughtworks.go.server.service.GoConfigService;
 import com.thoughtworks.go.serverhealth.ServerHealthService;
 import com.thoughtworks.go.service.ConfigRepository;
-import com.thoughtworks.go.util.*;
+import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother;
+import com.thoughtworks.go.util.SystemEnvironment;
+import com.thoughtworks.go.util.TimeProvider;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.jdom2.Document;
@@ -112,7 +114,7 @@ public class GoConfigMigrationIntegrationTest {
 
     @Test
     public void shouldMigrateToRevision22() throws Exception {
-        final String content = IOUtils.toString(getClass().getResourceAsStream("cruise-config-escaping-migration-test-fixture.xml"), UTF_8);
+        final String content = IOUtils.toString(getClass().getResource("cruise-config-escaping-migration-test-fixture.xml"), UTF_8);
 
         String migratedContent = ConfigMigrator.migrate(content, 21, 22);
 
@@ -122,7 +124,7 @@ public class GoConfigMigrationIntegrationTest {
 
     @Test
     public void shouldMigrateToRevision28() throws Exception {
-        final String content = IOUtils.toString(getClass().getResourceAsStream("no-tracking-tool-group-holder-config.xml"), UTF_8);
+        final String content = IOUtils.toString(getClass().getResource("no-tracking-tool-group-holder-config.xml"), UTF_8);
 
         String migratedContent = migrateXmlString(content, 27);
 
@@ -132,7 +134,7 @@ public class GoConfigMigrationIntegrationTest {
 
     @Test
     public void shouldMigrateToRevision34() throws Exception {
-        final String content = IOUtils.toString(getClass().getResourceAsStream("svn-p4-with-parameterized-passwords.xml"), UTF_8);
+        final String content = IOUtils.toString(getClass().getResource("svn-p4-with-parameterized-passwords.xml"), UTF_8);
 
         String migratedContent = ConfigMigrator.migrate(content, 22, 34);
 
@@ -144,7 +146,7 @@ public class GoConfigMigrationIntegrationTest {
 
     @Test
     public void shouldMigrateToRevision35_escapeHash() throws Exception {
-        final String content = IOUtils.toString(getClass().getResourceAsStream("escape_param_for_nant_p4.xml"), UTF_8).trim();
+        final String content = IOUtils.toString(getClass().getResource("escape_param_for_nant_p4.xml"), UTF_8).trim();
 
         String migratedContent = ConfigMigrator.migrate(content, 22, 35);
 
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 d8aba694df..d215589cb0 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
@@ -71,7 +71,7 @@ public class PipelineConfigsServiceIntegrationTest {
     @BeforeEach
     public void setUp() throws Exception {
         configHelper = new GoConfigFileHelper();
-        xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResourceAsStream("/data/config_with_pluggable_artifacts_store.xml"), UTF_8));
+        xml = goConfigMigration.upgradeIfNecessary(IOUtils.toString(getClass().getResource("/data/config_with_pluggable_artifacts_store.xml"), UTF_8));
         setupMetadataForPlugin();
 
         configHelper.usingCruiseConfigDao(goConfigDao);
@@ -201,7 +201,7 @@ public class PipelineConfigsServiceIntegrationTest {
     }
 
     private String groupSnippetWithSecurePropertiesBeforeEncryption() throws IOException {
-        return IOUtils.toString(getClass().getResourceAsStream("/data/pipeline_group_snippet_with_pluggable_artifacts.xml"), UTF_8);
+        return IOUtils.toString(getClass().getResource("/data/pipeline_group_snippet_with_pluggable_artifacts.xml"), UTF_8);
     }
 
 }