From 9868da8b5bbce3a584bb963d8f13333a37dc1f81 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Sat, 9 Mar 2024 11:03:42 +0300 Subject: [PATCH 1/8] Replace commons-io:commons-io --- build.gradle | 1 - .../wiremock/common/StreamSources.java | 14 ++- .../HandlebarsOptimizedTemplate.java | 10 +- .../wiremock/http/multipart/FileUpload.java | 84 +++++++++-------- .../tomakehurst/wiremock/DeadlockTest.java | 10 +- .../ResponseDribbleAcceptanceTest.java | 7 +- .../SavingMappingsAcceptanceTest.java | 27 +++--- .../wiremock/StandaloneAcceptanceTest.java | 91 ++++++++++--------- .../common/SingleRootFileSourceTest.java | 35 ++++--- .../JsonFileMappingsSourceTest.java | 33 ++++--- .../wiremock/testsupport/TestFiles.java | 4 +- .../wiremock/testsupport/WireMatchers.java | 7 +- testlogging/src/test/java/WiremockTest.java | 3 +- 13 files changed, 165 insertions(+), 161 deletions(-) diff --git a/build.gradle b/build.gradle index 7883a4a4b5..e6741628c1 100644 --- a/build.gradle +++ b/build.gradle @@ -98,7 +98,6 @@ dependencies { api 'commons-fileupload:commons-fileupload:1.5', { exclude group: 'commons-io', module: 'commons-io' } - api "commons-io:commons-io:2.15.1" api 'com.networknt:json-schema-validator:1.3.3' diff --git a/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java b/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java index dcb56744a5..cd4d537358 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java +++ b/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018-2022 Thomas Akehurst + * Copyright (C) 2018-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,4 +63,16 @@ public InputStream getStream() { public static InputStreamSource empty() { return forBytes(new byte[0]); } + + public static String getStringFromInputStream(InputStream inputStream) { + try { + StringBuilder sb = new StringBuilder(); + for (int ch; (ch = inputStream.read()) != -1; ) { + sb.append((char) ch); + } + return sb.toString(); + } catch (Exception ignored) { + return null; + } + } } diff --git a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java index c48674636e..0e9e9e8503 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java +++ b/src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/HandlebarsOptimizedTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019-2023 Thomas Akehurst + * Copyright (C) 2019-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import com.github.jknack.handlebars.Template; import com.github.tomakehurst.wiremock.common.Exceptions; import java.io.IOException; +import java.io.StringWriter; import java.io.Writer; -import org.apache.commons.io.output.StringBuilderWriter; public class HandlebarsOptimizedTemplate { @@ -44,9 +44,7 @@ public HandlebarsOptimizedTemplate(final Handlebars handlebars, final String con templateContent = content.substring( firstDelimStartPosition, lastDelimEndPosition + Handlebars.DELIM_END.length()); - endContent = - content.substring( - lastDelimEndPosition + Handlebars.DELIM_END.length(), content.length()); + endContent = content.substring(lastDelimEndPosition + Handlebars.DELIM_END.length()); } } @@ -71,7 +69,7 @@ public String apply(Object contextData) { private String applyTemplate(Context context) { return Exceptions.uncheck( () -> { - Writer stringWriter = new StringBuilderWriter(template.text().length() * 2); + Writer stringWriter = new StringWriter(template.text().length() * 2); template.apply(context, stringWriter); return stringWriter.toString(); }, diff --git a/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java b/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java index e64cccedc1..290f22ec83 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java +++ b/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2023 Thomas Akehurst + * Copyright (C) 2022-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,6 @@ import org.apache.commons.fileupload.util.FileItemHeadersImpl; import org.apache.commons.fileupload.util.LimitedInputStream; import org.apache.commons.fileupload.util.Streams; -import org.apache.commons.io.IOUtils; /** * The implementation is largely ported from {@link org.apache.commons.fileupload.FileUpload} and @@ -103,7 +102,7 @@ protected FileItemFactory getFileItemFactory() { * @throws FileUploadException if there are problems reading/parsing the request or storing files. */ public List parseRequest(RequestContext ctx) throws FileUploadException { - List items = new ArrayList(); + List items = new ArrayList<>(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); @@ -580,7 +579,7 @@ public void setHeaders(FileItemHeaders pHeaders) { : contentLengthInt; // CHECKSTYLE:ON - InputStream input; // N.B. this is eventually closed in MultipartStream processing + ; // N.B. this is eventually closed in MultipartStream processing if (sizeMax >= 0) { if (requestSize != -1 && requestSize > sizeMax) { throw new SizeLimitExceededException( @@ -590,50 +589,49 @@ public void setHeaders(FileItemHeaders pHeaders) { requestSize, sizeMax); } - // N.B. this is eventually closed in MultipartStream processing - input = - new LimitedInputStream(ctx.getInputStream(), sizeMax) { - @Override - protected void raiseError(long pSizeMax, long pCount) throws IOException { - FileUploadException ex = - new SizeLimitExceededException( - format( - "the request was rejected because its size (%s) exceeds the configured maximum (%s)", - pCount, pSizeMax), - pCount, - pSizeMax); - throw new FileUploadIOException(ex); - } - }; - } else { - input = ctx.getInputStream(); } - String charEncoding = headerEncoding; - if (charEncoding == null) { - charEncoding = ctx.getCharacterEncoding(); - } + try (InputStream input = + sizeMax >= 0 + ? new LimitedInputStream(ctx.getInputStream(), sizeMax) { + @Override + protected void raiseError(long pSizeMax, long pCount) throws IOException { + FileUploadException ex = + new SizeLimitExceededException( + format( + "the request was rejected because its size (%s) exceeds the configured maximum (%s)", + pCount, pSizeMax), + pCount, + pSizeMax); + throw new FileUploadIOException(ex); + } + } + : ctx.getInputStream(); ) { + String charEncoding = headerEncoding; + if (charEncoding == null) { + charEncoding = ctx.getCharacterEncoding(); + } - boundary = getBoundary(contentType); - if (boundary == null) { - IOUtils.closeQuietly(input); // avoid possible resource leak - throw new FileUploadException( - "the request was rejected because no multipart boundary was found"); - } + boundary = getBoundary(contentType); + if (boundary == null) { + throw new FileUploadException( + "the request was rejected because no multipart boundary was found"); + } - try { - multi = new MultipartStream(input, boundary, 4096, null); - } catch (IllegalArgumentException iae) { - IOUtils.closeQuietly(input); // avoid possible resource leak - throw new InvalidContentTypeException( - format( - "The boundary specified in the %s header is too long", FileUploadBase.CONTENT_TYPE), - iae); - } - multi.setHeaderEncoding(charEncoding); + try { + multi = new MultipartStream(input, boundary, 4096, null); + } catch (IllegalArgumentException iae) { + throw new InvalidContentTypeException( + format( + "The boundary specified in the %s header is too long", + FileUploadBase.CONTENT_TYPE), + iae); + } + multi.setHeaderEncoding(charEncoding); - skipPreamble = true; - findNextItem(); + skipPreamble = true; + findNextItem(); + } } /** diff --git a/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java b/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java index 8534c22c34..c47245c8ce 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019-2021 Thomas Akehurst + * Copyright (C) 2019-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.common.StreamSources.getStringFromInputStream; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; @@ -25,13 +26,10 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; -import java.io.InputStream; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; -import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.*; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; @@ -125,8 +123,6 @@ private void downloadContentAndMeasure(String urlDir, String expectedBody) throw } private String httpGetContent(HttpURLConnection connection) throws IOException { - try (InputStream is = connection.getInputStream()) { - return IOUtils.toString(is, StandardCharsets.UTF_8); - } + return getStringFromInputStream(connection.getInputStream()); } } diff --git a/src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java index d38797ce36..c6f0840b55 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/ResponseDribbleAcceptanceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017-2021 Thomas Akehurst + * Copyright (C) 2017-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ import com.github.tomakehurst.wiremock.http.HttpClientFactory; import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import java.io.IOException; -import org.apache.commons.io.IOUtils; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.core5.http.ClassicHttpResponse; @@ -80,7 +79,7 @@ public void requestIsSuccessfulButTakesLongerThanSocketTimeoutWhenDribbleIsEnabl long start = System.currentTimeMillis(); ClassicHttpResponse response = httpClient.execute(new HttpGet(wireMockRule.url("/delayedDribble"))); - byte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent()); + byte[] responseBody = response.getEntity().getContent().readAllBytes(); int duration = (int) (System.currentTimeMillis() - start); assertThat(response.getCode(), is(200)); @@ -121,7 +120,7 @@ public void requestIsSuccessfulAndBelowSocketTimeoutWhenDribbleIsDisabled() thro long start = System.currentTimeMillis(); ClassicHttpResponse response = httpClient.execute(new HttpGet(wireMockRule.url("/nonDelayedDribble"))); - byte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent()); + byte[] responseBody = response.getEntity().getContent().readAllBytes(); int duration = (int) (System.currentTimeMillis() - start); assertThat(response.getCode(), is(200)); diff --git a/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java index 1c0c4c0be2..2b6b65dff4 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013-2023 Thomas Akehurst + * Copyright (C) 2013-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,12 @@ import com.github.tomakehurst.wiremock.stubbing.StubMapping; import com.github.tomakehurst.wiremock.testsupport.WireMockResponse; import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Arrays; +import java.util.Comparator; import java.util.Objects; -import org.apache.commons.io.FileUtils; +import java.util.stream.Stream; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; @@ -41,8 +44,10 @@ public class SavingMappingsAcceptanceTest extends AcceptanceTestBase { private static void resetFileSourceRoot() { try { - if (FILE_SOURCE_ROOT.exists()) { - FileUtils.deleteDirectory(FILE_SOURCE_ROOT); + if (new File(String.valueOf(FILE_SOURCE_ROOT.toPath().toAbsolutePath())).exists()) { + try (Stream pathStream = Files.walk(FILE_SOURCE_ROOT.toPath().toAbsolutePath())) { + pathStream.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } } if (!FILES_DIRECTORY.mkdirs()) { throw new Exception("Could no create " + FILES_DIRECTORY.getAbsolutePath()); @@ -62,13 +67,13 @@ public static void setupServer() { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { resetFileSourceRoot(); reset(); } @Test - public void savesMappingsToMappingsDirectory() { + void savesMappingsToMappingsDirectory() { // Check the mapping we're about to add isn't already there WireMockResponse response = testClient.get("/some/url"); assertThat(response.statusCode(), is(404)); @@ -89,7 +94,7 @@ public void savesMappingsToMappingsDirectory() { } @Test - public void savedMappingIsDeletedFromTheDiskOnRemove() { + void savedMappingIsDeletedFromTheDiskOnRemove() { StubMapping stubMapping = stubFor(get("/delete/me").willReturn(ok())); saveAllMappings(); @@ -124,7 +129,7 @@ public void describeTo(Description description) { } @Test - public void doesNotDuplicateMappingsAlreadyPersistedToFileSystem() { + void doesNotDuplicateMappingsAlreadyPersistedToFileSystem() { // Check the mapping we're about to add isn't already there WireMockResponse response = testClient.get("/some/url"); assertThat(response.statusCode(), is(404)); @@ -137,11 +142,11 @@ public void doesNotDuplicateMappingsAlreadyPersistedToFileSystem() { saveAllMappings(); // Check only one file has been written - assertThat(MAPPINGS_DIRECTORY.listFiles().length, is(1)); + assertThat(Objects.requireNonNull(MAPPINGS_DIRECTORY.listFiles()).length, is(1)); } @Test - public void doesNotDuplicateMappingsAlreadyPersistedAfterReset() { + void doesNotDuplicateMappingsAlreadyPersistedAfterReset() { // Check the mapping we're about to add isn't already there WireMockResponse response = testClient.get("/some/url"); assertThat(response.statusCode(), is(404)); @@ -155,7 +160,7 @@ public void doesNotDuplicateMappingsAlreadyPersistedAfterReset() { saveAllMappings(); // Check only one file has been written - assertThat(MAPPINGS_DIRECTORY.listFiles().length, is(1)); + assertThat(Objects.requireNonNull(MAPPINGS_DIRECTORY.listFiles()).length, is(1)); } static final TypeSafeDiagnosingMatcher IS_PERSISTENT = diff --git a/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java index 890d840632..5953bd8331 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java @@ -38,15 +38,16 @@ import com.github.tomakehurst.wiremock.testsupport.WireMockResponse; import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient; import java.io.*; -import java.nio.charset.Charset; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.List; import java.util.function.Predicate; +import java.util.stream.Stream; import java.util.zip.GZIPInputStream; -import org.apache.commons.io.FileUtils; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -76,10 +77,11 @@ public class StandaloneAcceptanceTest { @BeforeEach public void init() throws Exception { - if (FILE_SOURCE_ROOT.exists()) { - FileUtils.deleteDirectory(FILE_SOURCE_ROOT); + if (new File(String.valueOf(FILE_SOURCE_ROOT.toPath().toAbsolutePath())).exists()) { + try (Stream pathStream = Files.walk(FILE_SOURCE_ROOT.toPath().toAbsolutePath())) { + pathStream.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } } - FILE_SOURCE_ROOT.mkdirs(); mappingsDirectory = new File(FILE_SOURCE_ROOT, MAPPINGS); @@ -101,7 +103,7 @@ public void stopServerRunner() { } @Test - public void acceptsMappingRequestOnDefaultPort() throws Exception { + void acceptsMappingRequestOnDefaultPort() { startRunner(); givenThat( get(urlEqualTo("/standalone/test/resource")) @@ -122,14 +124,14 @@ public void acceptsMappingRequestOnDefaultPort() throws Exception { + "} "; @Test - public void readsMappingFromMappingsDir() { + void readsMappingFromMappingsDir() { writeMappingFile("test-mapping-1.json", MAPPING_REQUEST); startRunner(); assertThat(testClient.get("/resource/from/file").content(), is("Body from mapping file")); } @Test - public void readsMappingFromSpecifiedRecordingsPath() { + void readsMappingFromSpecifiedRecordingsPath() { String differentRoot = FILE_SOURCE_ROOT + separator + "differentRoot"; writeFile(differentRoot + separator + underMappings("test-mapping-1.json"), MAPPING_REQUEST); startRunner("--root-dir", differentRoot); @@ -137,7 +139,7 @@ public void readsMappingFromSpecifiedRecordingsPath() { } @Test - public void servesFileFromFilesDir() { + void servesFileFromFilesDir() { writeFileToFilesDir("test-1.xml", "Blah"); startRunner(); WireMockResponse response = testClient.get("/test-1.xml"); @@ -147,7 +149,7 @@ public void servesFileFromFilesDir() { } @Test - public void servesFileFromSpecifiedRecordingsPath() { + void servesFileFromSpecifiedRecordingsPath() { String differentRoot = FILE_SOURCE_ROOT + separator + "differentRoot"; writeFile(differentRoot + separator + underFiles("test-1.xml"), "Blah"); startRunner("--root-dir", differentRoot); @@ -158,7 +160,7 @@ public void servesFileFromSpecifiedRecordingsPath() { } @Test - public void servesFileAsJsonWhenNoFileExtension() { + void servesFileAsJsonWhenNoFileExtension() { writeFileToFilesDir("json/12345", "{ \"key\": \"value\" }"); startRunner(); WireMockResponse response = testClient.get("/json/12345"); @@ -168,7 +170,7 @@ public void servesFileAsJsonWhenNoFileExtension() { } @Test - public void shouldNotSend302WhenPathIsDirAndTrailingSlashNotPresent() { + void shouldNotSend302WhenPathIsDirAndTrailingSlashNotPresent() { writeFileToFilesDir( "json/wire & mock directory/index.json", "{ \"key\": \"index page value\" }"); startRunner(); @@ -178,7 +180,7 @@ public void shouldNotSend302WhenPathIsDirAndTrailingSlashNotPresent() { } @Test - public void servesJsonIndexFileWhenTrailingSlashPresent() { + void servesJsonIndexFileWhenTrailingSlashPresent() { writeFileToFilesDir("json/23456/index.json", "{ \"key\": \"new value\" }"); startRunner(); WireMockResponse response = testClient.get("/json/23456/"); @@ -188,7 +190,7 @@ public void servesJsonIndexFileWhenTrailingSlashPresent() { } @Test - public void servesXmlIndexFileWhenTrailingSlashPresent() { + void servesXmlIndexFileWhenTrailingSlashPresent() { writeFileToFilesDir("json/34567/index.xml", "BLAB"); startRunner(); WireMockResponse response = testClient.get("/json/34567/"); @@ -198,7 +200,7 @@ public void servesXmlIndexFileWhenTrailingSlashPresent() { } @Test - public void doesNotServeFileFromFilesDirWhenNotGET() { + void doesNotServeFileFromFilesDirWhenNotGET() { writeFileToFilesDir("json/should-not-see-this.json", "{}"); startRunner(); WireMockResponse response = testClient.put("/json/should-not-see-this.json"); @@ -252,7 +254,7 @@ public void doesNotLogVerboselyWhenVerboseNotSetInCommandLine() { } @Test - public void startsOnPortSpecifiedOnCommandLine() throws Exception { + public void startsOnPortSpecifiedOnCommandLine() { int port = findFreePort(); startRunner("--port", "" + port); WireMock client = WireMock.create().host("localhost").port(port).build(); @@ -263,7 +265,7 @@ public void startsOnPortSpecifiedOnCommandLine() throws Exception { } @Test - public void proxiesToHostSpecifiedOnCommandLine() throws Exception { + void proxiesToHostSpecifiedOnCommandLine() { WireMock otherServerClient = startOtherServerAndClient(); otherServerClient.register( get(urlEqualTo("/proxy/ok?working=yes")).willReturn(aResponse().withStatus(HTTP_OK))); @@ -274,7 +276,7 @@ public void proxiesToHostSpecifiedOnCommandLine() throws Exception { } @Test - public void respondsWithPreExistingRecordingInProxyMode() throws Exception { + void respondsWithPreExistingRecordingInProxyMode() { writeMappingFile("test-mapping-2.json", BODY_FILE_MAPPING_REQUEST); writeFileToFilesDir("body-test.xml", "Existing recorded body"); @@ -289,7 +291,7 @@ public void respondsWithPreExistingRecordingInProxyMode() throws Exception { } @Test - public void recordsProxiedRequestsWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { + void recordsProxiedRequestsWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--record-mappings"); givenThat( @@ -308,7 +310,7 @@ public void recordsProxiedRequestsWhenSpecifiedOnCommandLineViaLegacyRecorder() } @Test - public void recordsRequestHeadersWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { + void recordsRequestHeadersWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--record-mappings", "--match-headers", "Accept"); givenThat( @@ -326,7 +328,7 @@ public void recordsRequestHeadersWhenSpecifiedOnCommandLineViaLegacyRecorder() t } @Test - public void recordsGzippedResponseBodiesDecompressedViaLegacyRecorder() { + void recordsGzippedResponseBodiesDecompressedViaLegacyRecorder() { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--record-mappings"); givenThat( @@ -358,12 +360,12 @@ void recordsGzippedResponseBodiesDecompressedViaNewRecorder(@TempDir Path tempFi Arrays.stream(requireNonNull(tempFileRoot.resolve("mappings").toFile().list())) .filter(name -> name.contains("record-this")) .findFirst() - .get(), + .orElse(""), endsWith(".json")); } @Test - public void matchesVeryLongHeader() { + void matchesVeryLongHeader() { startRunner("--jetty-header-buffer-size", "32678"); String veryLongHeader = padRight("", 16336).replace(' ', 'h'); @@ -379,7 +381,7 @@ public void matchesVeryLongHeader() { } @Test - public void performsBrowserProxyingWhenEnabled() throws Exception { + void performsBrowserProxyingWhenEnabled() { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--enable-browser-proxying"); otherServerClient.register( @@ -394,14 +396,14 @@ public void performsBrowserProxyingWhenEnabled() throws Exception { } @Test - public void doesNotRecordRequestWhenNotProxied() { + void doesNotRecordRequestWhenNotProxied() { startRunner("--record-mappings"); testClient.get("/try-to/record-this"); assertThat(mappingsDirectory, doesNotContainAFileWithNameContaining("try-to-record")); } @Test - public void doesNotRecordRequestWhenAlreadySeen() { + void doesNotRecordRequestWhenAlreadySeen() { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--record-mappings"); givenThat( @@ -418,7 +420,7 @@ public void doesNotRecordRequestWhenAlreadySeen() { } @Test - public void canBeShutDownRemotely() { + void canBeShutDownRemotely() { startRunner(); WireMock.shutdownServer(); @@ -434,7 +436,7 @@ public void canBeShutDownRemotely() { } @Test - public void canBeShutDownRemotelyWhenAsyncResponsesEnabled() { + void canBeShutDownRemotelyWhenAsyncResponsesEnabled() { startRunner("--async-response-enabled"); stubFor(get("/delay-this").willReturn(ok().withFixedDelay(50))); @@ -455,7 +457,7 @@ public void canBeShutDownRemotelyWhenAsyncResponsesEnabled() { } @Test - public void isRunningReturnsFalseBeforeRunMethodIsExecuted() { + void isRunningReturnsFalseBeforeRunMethodIsExecuted() { runner = new WireMockServerRunner(); assertThat(runner.isRunning(), is(false)); } @@ -473,7 +475,7 @@ public void isRunningReturnsFalseBeforeRunMethodIsExecuted() { + "} "; @Test - public void failsWithUsefulErrorMessageWhenMappingFileIsInvalid() { + void failsWithUsefulErrorMessageWhenMappingFileIsInvalid() { writeMappingFile("bad-mapping.json", BAD_MAPPING); MappingFileException exception = assertThrows(MappingFileException.class, this::startRunner); @@ -501,11 +503,12 @@ void savesMappingFileOnCreationOfPersistentStub() { } private String contentsOfFirstFileNamedLike(String namePart) throws IOException { - return FileUtils.readFileToString(firstFileWithNameLike(mappingsDirectory, namePart), UTF_8); + return Files.readString( + requireNonNull(firstFileWithNameLike(mappingsDirectory, namePart)).toPath()); } private File firstFileWithNameLike(File directory, String namePart) { - for (File file : directory.listFiles(namedLike(namePart))) { + for (File file : requireNonNull(directory.listFiles(namedLike(namePart)))) { return file; } @@ -576,7 +579,7 @@ private void startRunner(String... args) { } private String[] argsWithRecordingsPath(String[] args) { - List argsAsList = new ArrayList(asList(args)); + List argsAsList = new ArrayList<>(asList(args)); if (!argsAsList.contains("--root-dir")) { argsAsList.addAll(asList("--root-dir", FILE_SOURCE_ROOT.getPath())); } @@ -584,7 +587,7 @@ private String[] argsWithRecordingsPath(String[] args) { } private String[] argsWithPort(String[] args) { - List argsAsList = new ArrayList(asList(args)); + List argsAsList = new ArrayList<>(asList(args)); if (!argsAsList.contains("--port")) { argsAsList.addAll(asList("--port", "" + Options.DYNAMIC_PORT)); } @@ -600,15 +603,15 @@ private void startRecordingSystemOutAndErr() { } private String systemOutText() { - return new String(out.toByteArray()); + return out.toString(); } private String systemErrText() { - return new String(err.toByteArray()); + return err.toString(); } private Matcher containsAFileContaining(final String expectedContents) { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override public void describeTo(Description desc) { @@ -617,9 +620,9 @@ public void describeTo(Description desc) { @Override public boolean matchesSafely(File dir) { - for (File file : dir.listFiles()) { + for (File file : requireNonNull(dir.listFiles())) { try { - if (FileUtils.readFileToString(file, UTF_8).contains(expectedContents)) { + if (Files.readString(file.toPath()).contains(expectedContents)) { return true; } } catch (IOException e) { @@ -633,7 +636,7 @@ public boolean matchesSafely(File dir) { } private Matcher doesNotContainAFileWithNameContaining(final String namePart) { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override public void describeTo(Description desc) { @@ -681,12 +684,12 @@ private String decompress(byte[] content) { byte[] buf = new byte[8192]; - int read = -1; + int read; while ((read = gin.read(buf)) != -1) { baos.write(buf, 0, read); } - return new String(baos.toByteArray(), Charset.forName(UTF_8.name())); + return baos.toString(UTF_8); } catch (IOException e) { return null; @@ -694,8 +697,8 @@ private String decompress(byte[] content) { if (gin != null) try { gin.close(); - } catch (IOException e) { - + } catch (IOException ignored) { + // ignored } } } diff --git a/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java b/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java index 23de02970e..db0645ddd8 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011-2022 Thomas Akehurst + * Copyright (C) 2011-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,10 @@ import com.github.tomakehurst.wiremock.security.NotAuthorisedException; import java.io.File; -import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; -import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; public class SingleRootFileSourceTest { @@ -38,7 +36,7 @@ public class SingleRootFileSourceTest { @SuppressWarnings("unchecked") @Test - public void listsTextFilesRecursively() { + void listsTextFilesRecursively() { SingleRootFileSource fileSource = new SingleRootFileSource(ROOT_PATH); List files = fileSource.listFilesRecursively(); @@ -58,9 +56,9 @@ public void listsTextFilesRecursively() { } @Test - public void writesTextFileEvenWhenRootIsARelativePath() throws IOException { + void writesTextFileEvenWhenRootIsARelativePath() { String relativeRootPath = "./target/tmp/"; - FileUtils.forceMkdir(new File(relativeRootPath)); + new File(relativeRootPath).mkdir(); SingleRootFileSource fileSource = new SingleRootFileSource(relativeRootPath); Path fileAbsolutePath = Paths.get(relativeRootPath).toAbsolutePath().resolve("myFile"); fileSource.writeTextFile(fileAbsolutePath.toString(), "stuff"); @@ -69,7 +67,7 @@ public void writesTextFileEvenWhenRootIsARelativePath() throws IOException { } @Test - public void listFilesRecursivelyThrowsExceptionWhenRootIsNotDir() { + void listFilesRecursivelyThrowsExceptionWhenRootIsNotDir() { assertThrows( RuntimeException.class, () -> { @@ -80,7 +78,7 @@ public void listFilesRecursivelyThrowsExceptionWhenRootIsNotDir() { } @Test - public void writeThrowsExceptionWhenRootIsNotDir() { + void writeThrowsExceptionWhenRootIsNotDir() { assertThrows( RuntimeException.class, () -> { @@ -91,8 +89,7 @@ public void writeThrowsExceptionWhenRootIsNotDir() { } @Test - public void - listFilesRecursivelyThrowsExceptionWhenLastPathNodeIsSimilarToRootButWithExtraCharacters() { + void listFilesRecursivelyThrowsExceptionWhenLastPathNodeIsSimilarToRootButWithExtraCharacters() { assertThrows( NotAuthorisedException.class, () -> { @@ -103,7 +100,7 @@ public void writeThrowsExceptionWhenRootIsNotDir() { } @Test - public void writeTextFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() { + void writeTextFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -113,7 +110,7 @@ public void writeTextFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() { } @Test - public void writeTextFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() { + void writeTextFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -124,7 +121,7 @@ public void writeTextFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() { } @Test - public void writeBinaryFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() { + void writeBinaryFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -134,7 +131,7 @@ public void writeBinaryFileThrowsExceptionWhenGivenRelativePathNotUnderRoot() { } @Test - public void writeBinaryFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() { + void writeBinaryFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -145,7 +142,7 @@ public void writeBinaryFileThrowsExceptionWhenGivenAbsolutePathNotUnderRoot() { } @Test - public void deleteThrowsExceptionWhenGivenPathNotUnderRoot() { + void deleteThrowsExceptionWhenGivenPathNotUnderRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -156,7 +153,7 @@ public void deleteThrowsExceptionWhenGivenPathNotUnderRoot() { } @Test - public void readBinaryFileThrowsExceptionWhenRelativePathIsOutsideRoot() { + void readBinaryFileThrowsExceptionWhenRelativePathIsOutsideRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -166,7 +163,7 @@ public void readBinaryFileThrowsExceptionWhenRelativePathIsOutsideRoot() { } @Test - public void readTextFileThrowsExceptionWhenRelativePathIsOutsideRoot() { + void readTextFileThrowsExceptionWhenRelativePathIsOutsideRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -176,7 +173,7 @@ public void readTextFileThrowsExceptionWhenRelativePathIsOutsideRoot() { } @Test - public void readBinaryFileThrowsExceptionWhenAbsolutePathIsOutsideRoot() throws Exception { + public void readBinaryFileThrowsExceptionWhenAbsolutePathIsOutsideRoot() { assertThrows( NotAuthorisedException.class, () -> { @@ -187,7 +184,7 @@ public void readBinaryFileThrowsExceptionWhenAbsolutePathIsOutsideRoot() throws } @Test - public void readTextFileThrowsExceptionWhenAbsolutePathIsOutsideRoot() throws Exception { + void readTextFileThrowsExceptionWhenAbsolutePathIsOutsideRoot() { assertThrows( NotAuthorisedException.class, () -> { diff --git a/src/test/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSourceTest.java b/src/test/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSourceTest.java index ce117fc220..91ca405c04 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSourceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/standalone/JsonFileMappingsSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016-2023 Thomas Akehurst + * Copyright (C) 2016-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.ok; import static com.github.tomakehurst.wiremock.testsupport.TestFiles.filePath; -import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -37,13 +36,13 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; -import org.apache.commons.io.FileUtils; +import java.util.Objects; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -public class JsonFileMappingsSourceTest { +class JsonFileMappingsSourceTest { @TempDir public File tempDir; @@ -80,7 +79,7 @@ private void load() { } @Test - public void loadsMappingsViaClasspathFileSource() { + void loadsMappingsViaClasspathFileSource() { ClasspathFileSource fileSource = new ClasspathFileSource("jar-filesource"); JsonFileMappingsSource source = new JsonFileMappingsSource(fileSource, new FilenameMaker()); StoreBackedStubMappings stubMappings = new InMemoryStubMappings(); @@ -96,21 +95,21 @@ public void loadsMappingsViaClasspathFileSource() { } @Test - public void stubMappingFilesAreWrittenWithInsertionIndex() throws Exception { + void stubMappingFilesAreWrittenWithInsertionIndex() throws Exception { JsonFileMappingsSource source = new JsonFileMappingsSource(new SingleRootFileSource(tempDir), new FilenameMaker()); StubMapping stub = get("/saveable").willReturn(ok()).build(); source.save(stub); - File savedFile = tempDir.listFiles()[0]; - String savedStub = FileUtils.readFileToString(savedFile, UTF_8); + File savedFile = Objects.requireNonNull(tempDir.listFiles())[0]; + String savedStub = Files.readString(savedFile.toPath()); assertThat(savedStub, containsString("\"insertionIndex\" : 0")); } @Test - public void stubMappingFilesWithOwnFileTemplateFormat() { + void stubMappingFilesWithOwnFileTemplateFormat() { JsonFileMappingsSource source = new JsonFileMappingsSource( new SingleRootFileSource(tempDir), @@ -119,13 +118,13 @@ public void stubMappingFilesWithOwnFileTemplateFormat() { StubMapping stub = get("/saveable").willReturn(ok()).build(); source.save(stub); - File savedFile = tempDir.listFiles()[0]; + File savedFile = Objects.requireNonNull(tempDir.listFiles())[0]; - assertEquals(savedFile.getName(), "get-saveable.json"); + assertEquals("get-saveable.json", savedFile.getName()); } @Test - public void refusesToRemoveStubMappingContainedInMultiFile() throws Exception { + void refusesToRemoveStubMappingContainedInMultiFile() throws Exception { configureWithMultipleMappingFile(); StubMapping firstStub = stubMappings.getAll().get(0); @@ -145,7 +144,7 @@ public void refusesToRemoveStubMappingContainedInMultiFile() throws Exception { } @Test - public void refusesToRemoveAllWhenMultiMappingFilesArePresent() throws Exception { + void refusesToRemoveAllWhenMultiMappingFilesArePresent() throws Exception { configureWithMultipleMappingFile(); try { @@ -163,7 +162,7 @@ public void refusesToRemoveAllWhenMultiMappingFilesArePresent() throws Exception } @Test - public void refusesToSaveStubMappingOriginallyLoadedFromMultiMappingFile() throws Exception { + void refusesToSaveStubMappingOriginallyLoadedFromMultiMappingFile() throws Exception { configureWithMultipleMappingFile(); StubMapping firstStub = stubMappings.getAll().get(0); @@ -182,18 +181,18 @@ public void refusesToSaveStubMappingOriginallyLoadedFromMultiMappingFile() throw } @Test - public void savesStubMappingOriginallyLoadedFromSingleMappingFile() throws Exception { + void savesStubMappingOriginallyLoadedFromSingleMappingFile() throws Exception { configureWithSingleMappingFile(); StubMapping firstStub = stubMappings.getAll().get(0); firstStub.setName("New name"); source.save(firstStub); - assertThat(FileUtils.readFileToString(stubMappingFile, UTF_8), containsString("New name")); + assertThat(Files.readString(stubMappingFile.toPath()), containsString("New name")); } @Test - public void removesStubMappingOriginallyLoadedFromSingleMappingFile() throws Exception { + void removesStubMappingOriginallyLoadedFromSingleMappingFile() throws Exception { configureWithSingleMappingFile(); StubMapping firstStub = stubMappings.getAll().get(0); diff --git a/src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java b/src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java index ff54a8714d..6f7cf8afa9 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java +++ b/src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java @@ -17,7 +17,6 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked; import static com.github.tomakehurst.wiremock.common.ResourceUtil.*; -import static java.nio.charset.StandardCharsets.UTF_8; import java.io.File; import java.io.IOException; @@ -32,6 +31,7 @@ public class TestFiles { public static final String KEY_STORE_PATH = filePath("test-keystore"); public static final String KEY_STORE_WITH_CA_PATH = filePath("test-keystore-with-ca"); + // TODO still needed 1.7 ? private static String getTrustStoreRelativeName() { return System.getProperty("java.specification.version").equals("1.7") ? "test-truststore.jks" @@ -44,7 +44,7 @@ public static String defaultTestFilesRoot() { public static String file(String path) { try { - String text = Files.readString(getResourcePath(TestFiles.class, path), UTF_8); + String text = Files.readString(getResourcePath(TestFiles.class, path)); if (System.getProperty("os.name").startsWith("Windows")) { text = text.replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); } diff --git a/src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java b/src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java index 7e7f8a556f..235ea2390c 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java +++ b/src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011-2023 Thomas Akehurst + * Copyright (C) 2011-2024 Thomas Akehurst * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import com.github.tomakehurst.wiremock.stubbing.StubMapping; 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.text.ParseException; import java.text.SimpleDateFormat; @@ -43,7 +43,6 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import org.apache.commons.io.FileUtils; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; @@ -379,7 +378,7 @@ public boolean matches(Object actualValue) { private static String fileContents(File input) { try { - return FileUtils.readFileToString(input, StandardCharsets.UTF_8); + return Files.readString(input.toPath()); } catch (IOException e) { return throwUnchecked(e, String.class); } diff --git a/testlogging/src/test/java/WiremockTest.java b/testlogging/src/test/java/WiremockTest.java index be8143f53f..bfc60b98ad 100644 --- a/testlogging/src/test/java/WiremockTest.java +++ b/testlogging/src/test/java/WiremockTest.java @@ -1,5 +1,4 @@ import com.github.tomakehurst.wiremock.junit.WireMockRule; -import org.apache.commons.io.IOUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -44,7 +43,7 @@ public void useWireMock() throws IOException { URL uri = new URL("http://localhost:8080/blah"); InputStream content = uri.openConnection().getInputStream(); - final String retrievedBody = IOUtils.toString(content, UTF_8); + final String retrievedBody = getStringFromInputStream(content); assertEquals("body", retrievedBody); assertThat(stdOutCapture.toString(), containsString("LOGBACK INFO w.o.e.j.s.h.ContextHandler.__admin - RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.AdminRequestHandler")); } From dbede0dda6c558db6de2870548fb8a3eb08dff42 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Sat, 9 Mar 2024 13:53:14 +0300 Subject: [PATCH 2/8] Replace commons-io:commons-io --- .../tomakehurst/wiremock/common/SingleRootFileSourceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java b/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java index db0645ddd8..ad1c52c2a1 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java @@ -58,7 +58,7 @@ void listsTextFilesRecursively() { @Test void writesTextFileEvenWhenRootIsARelativePath() { String relativeRootPath = "./target/tmp/"; - new File(relativeRootPath).mkdir(); + new File(String.valueOf(Paths.get(relativeRootPath).toAbsolutePath())).mkdir(); SingleRootFileSource fileSource = new SingleRootFileSource(relativeRootPath); Path fileAbsolutePath = Paths.get(relativeRootPath).toAbsolutePath().resolve("myFile"); fileSource.writeTextFile(fileAbsolutePath.toString(), "stuff"); From a92217ef132451e89ad24cb920d227b22e825d09 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Sat, 9 Mar 2024 14:03:52 +0300 Subject: [PATCH 3/8] Replace commons-io:commons-io --- .../tomakehurst/wiremock/common/SingleRootFileSourceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java b/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java index ad1c52c2a1..38455ec8a6 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/common/SingleRootFileSourceTest.java @@ -58,7 +58,7 @@ void listsTextFilesRecursively() { @Test void writesTextFileEvenWhenRootIsARelativePath() { String relativeRootPath = "./target/tmp/"; - new File(String.valueOf(Paths.get(relativeRootPath).toAbsolutePath())).mkdir(); + new File(String.valueOf(Paths.get(relativeRootPath).toAbsolutePath())).mkdirs(); SingleRootFileSource fileSource = new SingleRootFileSource(relativeRootPath); Path fileAbsolutePath = Paths.get(relativeRootPath).toAbsolutePath().resolve("myFile"); fileSource.writeTextFile(fileAbsolutePath.toString(), "stuff"); From 6e944b7c671d03dc397c2e15c4b7ccbe16d300d6 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Sat, 9 Mar 2024 22:26:57 +0300 Subject: [PATCH 4/8] Replace commons-io:commons-io --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index e6741628c1..7087d53fb0 100644 --- a/build.gradle +++ b/build.gradle @@ -118,7 +118,7 @@ dependencies { testImplementation 'com.toomuchcoding.jsonassert:jsonassert:0.8.0' testImplementation 'org.awaitility:awaitility:4.2.0' testImplementation "com.googlecode.jarjar:jarjar:1.3" - testImplementation "commons-io:commons-io:2.15.1" + testRuntimeOnly "commons-io:commons-io:2.15.1" testImplementation 'org.scala-lang:scala-library:2.13.13' testImplementation 'com.tngtech.archunit:archunit-junit5:0.23.1' From 6bee13d76871555c5cb730a15074a47c56cde2c5 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Sat, 9 Mar 2024 22:40:51 +0300 Subject: [PATCH 5/8] Replace commons-io:commons-io --- .../github/tomakehurst/wiremock/http/multipart/FileUpload.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java b/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java index 290f22ec83..e74545886c 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java +++ b/src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileUpload.java @@ -606,7 +606,7 @@ protected void raiseError(long pSizeMax, long pCount) throws IOException { throw new FileUploadIOException(ex); } } - : ctx.getInputStream(); ) { + : ctx.getInputStream()) { String charEncoding = headerEncoding; if (charEncoding == null) { charEncoding = ctx.getCharacterEncoding(); From 294888fd612cd47201b2929559ef63f24773a690 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Sat, 9 Mar 2024 23:18:28 +0300 Subject: [PATCH 6/8] Replace commons-io:commons-io --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 7087d53fb0..e6741628c1 100644 --- a/build.gradle +++ b/build.gradle @@ -118,7 +118,7 @@ dependencies { testImplementation 'com.toomuchcoding.jsonassert:jsonassert:0.8.0' testImplementation 'org.awaitility:awaitility:4.2.0' testImplementation "com.googlecode.jarjar:jarjar:1.3" - testRuntimeOnly "commons-io:commons-io:2.15.1" + testImplementation "commons-io:commons-io:2.15.1" testImplementation 'org.scala-lang:scala-library:2.13.13' testImplementation 'com.tngtech.archunit:archunit-junit5:0.23.1' From b9b3403d1f99a54264f277c8b343673803340826 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Thu, 28 Mar 2024 12:36:19 +0300 Subject: [PATCH 7/8] Update --- .../com/github/tomakehurst/wiremock/testsupport/TestFiles.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java b/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java index be6edbecfd..2a93378095 100644 --- a/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java +++ b/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java @@ -18,7 +18,6 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked; import static com.github.tomakehurst.wiremock.common.ResourceUtil.getResourcePath; import static com.github.tomakehurst.wiremock.common.ResourceUtil.getResourceURI; -import static java.nio.charset.StandardCharsets.UTF_8; import java.io.File; import java.io.IOException; @@ -45,7 +44,7 @@ public static String defaultTestFilesRoot() { public static String file(String path) { try { - String text = Files.readString(getResourcePath(TestFiles.class, path), UTF_8); + String text = Files.readString(getResourcePath(TestFiles.class, path)); if (System.getProperty("os.name").startsWith("Windows")) { text = text.replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); } From a914add1b66a0f27acc273e330ed6a32163ce799 Mon Sep 17 00:00:00 2001 From: Kirill Peshin Date: Sat, 30 Mar 2024 07:43:14 +0300 Subject: [PATCH 8/8] Update --- .../tomakehurst/wiremock/common/StreamSources.java | 12 ------------ .../github/tomakehurst/wiremock/DeadlockTest.java | 10 ++++++++-- .../wiremock/SavingMappingsAcceptanceTest.java | 2 +- .../wiremock/StandaloneAcceptanceTest.java | 2 +- testlogging/src/test/java/WiremockTest.java | 7 ++++++- 5 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java b/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java index cd4d537358..eab3c3a5b9 100644 --- a/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java +++ b/src/main/java/com/github/tomakehurst/wiremock/common/StreamSources.java @@ -63,16 +63,4 @@ public InputStream getStream() { public static InputStreamSource empty() { return forBytes(new byte[0]); } - - public static String getStringFromInputStream(InputStream inputStream) { - try { - StringBuilder sb = new StringBuilder(); - for (int ch; (ch = inputStream.read()) != -1; ) { - sb.append((char) ch); - } - return sb.toString(); - } catch (Exception ignored) { - return null; - } - } } diff --git a/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java b/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java index c47245c8ce..8a64e57552 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java @@ -18,7 +18,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.common.StreamSources.getStringFromInputStream; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; @@ -26,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; +import java.io.InputStream; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; @@ -123,6 +123,12 @@ private void downloadContentAndMeasure(String urlDir, String expectedBody) throw } private String httpGetContent(HttpURLConnection connection) throws IOException { - return getStringFromInputStream(connection.getInputStream()); + try (InputStream is = connection.getInputStream()) { + StringBuilder sb = new StringBuilder(); + for (int ch; (ch = is.read()) != -1; ) { + sb.append((char) ch); + } + return sb.toString(); + } } } diff --git a/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java index 2b6b65dff4..7cdeb08db3 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/SavingMappingsAcceptanceTest.java @@ -44,7 +44,7 @@ public class SavingMappingsAcceptanceTest extends AcceptanceTestBase { private static void resetFileSourceRoot() { try { - if (new File(String.valueOf(FILE_SOURCE_ROOT.toPath().toAbsolutePath())).exists()) { + if (FILE_SOURCE_ROOT.exists()) { try (Stream pathStream = Files.walk(FILE_SOURCE_ROOT.toPath().toAbsolutePath())) { pathStream.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } diff --git a/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java index d7ad91cfc0..a23c9c3e4a 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java @@ -78,7 +78,7 @@ public class StandaloneAcceptanceTest { @BeforeEach public void init() throws Exception { - if (new File(String.valueOf(FILE_SOURCE_ROOT.toPath().toAbsolutePath())).exists()) { + if (FILE_SOURCE_ROOT.exists()) { try (Stream pathStream = Files.walk(FILE_SOURCE_ROOT.toPath().toAbsolutePath())) { pathStream.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } diff --git a/testlogging/src/test/java/WiremockTest.java b/testlogging/src/test/java/WiremockTest.java index bfc60b98ad..71522a4da6 100644 --- a/testlogging/src/test/java/WiremockTest.java +++ b/testlogging/src/test/java/WiremockTest.java @@ -43,7 +43,12 @@ public void useWireMock() throws IOException { URL uri = new URL("http://localhost:8080/blah"); InputStream content = uri.openConnection().getInputStream(); - final String retrievedBody = getStringFromInputStream(content); + StringBuilder sb = new StringBuilder(); + for (int ch; (ch = inputStream.read()) != -1; ) { + sb.append((char) ch); + } + + final String retrievedBody = sb.toString(); assertEquals("body", retrievedBody); assertThat(stdOutCapture.toString(), containsString("LOGBACK INFO w.o.e.j.s.h.ContextHandler.__admin - RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.AdminRequestHandler")); }