diff --git a/build.gradle b/build.gradle index d793509795..66c0761289 100644 --- a/build.gradle +++ b/build.gradle @@ -99,7 +99,6 @@ dependencies { api 'commons-fileupload:commons-fileupload:1.5', { exclude group: 'commons-io', module: 'commons-io' } - api "commons-io:commons-io:2.16.0" api 'com.networknt:json-schema-validator:1.4.0' 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..eab3c3a5b9 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. 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 8f5e908b40..d711caea14 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 @@ -21,8 +21,8 @@ import com.github.tomakehurst.wiremock.common.Exceptions; import com.github.tomakehurst.wiremock.common.RequestCache; import java.io.IOException; +import java.io.StringWriter; import java.io.Writer; -import org.apache.commons.io.output.StringBuilderWriter; public class HandlebarsOptimizedTemplate { @@ -45,9 +45,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()); } } @@ -72,7 +70,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..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 @@ -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..8a64e57552 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. @@ -29,9 +29,7 @@ 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; @@ -126,7 +124,11 @@ 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); + 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/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..7cdeb08db3 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; @@ -42,7 +45,9 @@ public class SavingMappingsAcceptanceTest extends AcceptanceTestBase { private static void resetFileSourceRoot() { try { if (FILE_SOURCE_ROOT.exists()) { - FileUtils.deleteDirectory(FILE_SOURCE_ROOT); + 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 1deeb69200..a23c9c3e4a 100644 --- a/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java +++ b/src/test/java/com/github/tomakehurst/wiremock/StandaloneAcceptanceTest.java @@ -39,15 +39,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; @@ -78,9 +79,10 @@ public class StandaloneAcceptanceTest { @BeforeEach public void init() throws Exception { if (FILE_SOURCE_ROOT.exists()) { - FileUtils.deleteDirectory(FILE_SOURCE_ROOT); + 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); @@ -102,7 +104,7 @@ public void stopServerRunner() { } @Test - public void acceptsMappingRequestOnDefaultPort() throws Exception { + void acceptsMappingRequestOnDefaultPort() { startRunner(); givenThat( get(urlEqualTo("/standalone/test/resource")) @@ -123,14 +125,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); @@ -138,7 +140,7 @@ public void readsMappingFromSpecifiedRecordingsPath() { } @Test - public void servesFileFromFilesDir() { + void servesFileFromFilesDir() { writeFileToFilesDir("test-1.xml", "Blah"); startRunner(); WireMockResponse response = testClient.get("/test-1.xml"); @@ -148,7 +150,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); @@ -159,7 +161,7 @@ public void servesFileFromSpecifiedRecordingsPath() { } @Test - public void servesFileAsJsonWhenNoFileExtension() { + void servesFileAsJsonWhenNoFileExtension() { writeFileToFilesDir("json/12345", "{ \"key\": \"value\" }"); startRunner(); WireMockResponse response = testClient.get("/json/12345"); @@ -174,7 +176,7 @@ public void servesFileAsJsonWhenNoFileExtension() { reason = "Jetty 12 and above always redirects when folder (without trailing slash) is accessed") @Test - public void shouldNotSend302WhenPathIsDirAndTrailingSlashNotPresent() { + void shouldNotSend302WhenPathIsDirAndTrailingSlashNotPresent() { writeFileToFilesDir( "json/wire & mock directory/index.json", "{ \"key\": \"index page value\" }"); startRunner(); @@ -197,7 +199,7 @@ public void shouldSend302WhenPathIsDirAndTrailingSlashNotPresent() { } @Test - public void servesJsonIndexFileWhenTrailingSlashPresent() { + void servesJsonIndexFileWhenTrailingSlashPresent() { writeFileToFilesDir("json/23456/index.json", "{ \"key\": \"new value\" }"); startRunner(); WireMockResponse response = testClient.get("/json/23456/"); @@ -208,7 +210,7 @@ public void servesJsonIndexFileWhenTrailingSlashPresent() { } @Test - public void servesXmlIndexFileWhenTrailingSlashPresent() { + void servesXmlIndexFileWhenTrailingSlashPresent() { writeFileToFilesDir("json/34567/index.xml", "BLAB"); startRunner(); WireMockResponse response = testClient.get("/json/34567/"); @@ -218,7 +220,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"); @@ -272,7 +274,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(); @@ -283,7 +285,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))); @@ -294,7 +296,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"); @@ -309,7 +311,7 @@ public void respondsWithPreExistingRecordingInProxyMode() throws Exception { } @Test - public void recordsProxiedRequestsWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { + void recordsProxiedRequestsWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--record-mappings"); givenThat( @@ -328,7 +330,7 @@ public void recordsProxiedRequestsWhenSpecifiedOnCommandLineViaLegacyRecorder() } @Test - public void recordsRequestHeadersWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { + void recordsRequestHeadersWhenSpecifiedOnCommandLineViaLegacyRecorder() throws Exception { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--record-mappings", "--match-headers", "Accept"); givenThat( @@ -346,7 +348,7 @@ public void recordsRequestHeadersWhenSpecifiedOnCommandLineViaLegacyRecorder() t } @Test - public void recordsGzippedResponseBodiesDecompressedViaLegacyRecorder() { + void recordsGzippedResponseBodiesDecompressedViaLegacyRecorder() { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--record-mappings"); givenThat( @@ -378,12 +380,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'); @@ -399,7 +401,7 @@ public void matchesVeryLongHeader() { } @Test - public void performsBrowserProxyingWhenEnabled() throws Exception { + void performsBrowserProxyingWhenEnabled() { WireMock otherServerClient = startOtherServerAndClient(); startRunner("--enable-browser-proxying"); otherServerClient.register( @@ -414,14 +416,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( @@ -438,7 +440,7 @@ public void doesNotRecordRequestWhenAlreadySeen() { } @Test - public void canBeShutDownRemotely() { + void canBeShutDownRemotely() { startRunner(); WireMock.shutdownServer(); @@ -454,7 +456,7 @@ public void canBeShutDownRemotely() { } @Test - public void canBeShutDownRemotelyWhenAsyncResponsesEnabled() { + void canBeShutDownRemotelyWhenAsyncResponsesEnabled() { startRunner("--async-response-enabled"); stubFor(get("/delay-this").willReturn(ok().withFixedDelay(50))); @@ -475,7 +477,7 @@ public void canBeShutDownRemotelyWhenAsyncResponsesEnabled() { } @Test - public void isRunningReturnsFalseBeforeRunMethodIsExecuted() { + void isRunningReturnsFalseBeforeRunMethodIsExecuted() { runner = new WireMockServerRunner(); assertThat(runner.isRunning(), is(false)); } @@ -493,7 +495,7 @@ public void isRunningReturnsFalseBeforeRunMethodIsExecuted() { + "} "; @Test - public void failsWithUsefulErrorMessageWhenMappingFileIsInvalid() { + void failsWithUsefulErrorMessageWhenMappingFileIsInvalid() { writeMappingFile("bad-mapping.json", BAD_MAPPING); MappingFileException exception = assertThrows(MappingFileException.class, this::startRunner); @@ -521,11 +523,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; } @@ -596,7 +599,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())); } @@ -604,7 +607,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)); } @@ -620,15 +623,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) { @@ -637,9 +640,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) { @@ -653,7 +656,7 @@ public boolean matchesSafely(File dir) { } private Matcher doesNotContainAFileWithNameContaining(final String namePart) { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override public void describeTo(Description desc) { @@ -701,12 +704,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; @@ -714,8 +717,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..38455ec8a6 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(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"); @@ -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/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"); } diff --git a/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java b/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java index 30ee8ea0fb..505c283c71 100644 --- a/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java +++ b/src/testFixtures/java/com/github/tomakehurst/wiremock/testsupport/WireMatchers.java @@ -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; @@ -38,7 +38,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; @@ -374,7 +373,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..71522a4da6 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,12 @@ 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); + 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")); }