Skip to content

Commit

Permalink
Merge pull request wiremock#2632 from pks-1981/commons_io
Browse files Browse the repository at this point in the history
Replace commons-io:commons-io
  • Loading branch information
leeturner authored Apr 3, 2024
2 parents e268a24 + 96b0a43 commit a7f76a7
Show file tree
Hide file tree
Showing 13 changed files with 156 additions and 154 deletions.
1 change: 0 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand All @@ -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());
}
}

Expand All @@ -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();
},
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -103,7 +102,7 @@ protected FileItemFactory getFileItemFactory() {
* @throws FileUploadException if there are problems reading/parsing the request or storing files.
*/
public List<FileItem> parseRequest(RequestContext ctx) throws FileUploadException {
List<FileItem> items = new ArrayList<FileItem>();
List<FileItem> items = new ArrayList<>();
boolean successful = false;
try {
FileItemIterator iter = getItemIterator(ctx);
Expand Down Expand Up @@ -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(
Expand All @@ -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();
}
}

/**
Expand Down
10 changes: 6 additions & 4 deletions src/test/java/com/github/tomakehurst/wiremock/DeadlockTest.java
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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();
}
}
}
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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));
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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;
Expand All @@ -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<Path> 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());
Expand All @@ -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));
Expand All @@ -89,7 +94,7 @@ public void savesMappingsToMappingsDirectory() {
}

@Test
public void savedMappingIsDeletedFromTheDiskOnRemove() {
void savedMappingIsDeletedFromTheDiskOnRemove() {
StubMapping stubMapping = stubFor(get("/delete/me").willReturn(ok()));
saveAllMappings();

Expand Down Expand Up @@ -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));
Expand All @@ -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));
Expand All @@ -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<StubMapping> IS_PERSISTENT =
Expand Down
Loading

0 comments on commit a7f76a7

Please sign in to comment.