Skip to content

Commit

Permalink
fix: fixed filename extraction from URL (#1742)
Browse files Browse the repository at this point in the history
If the URL contained slashes in the parameter part of the URL, the
filename extraction would fail.

Fixes #1740
  • Loading branch information
quintesse committed Feb 3, 2024
1 parent f5d8300 commit 7a8bc7d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/main/java/dev/jbang/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,12 @@ private static String extractFileName(URLConnection urlConnection) throws IOExce
if (isBlankString(fileName)) {
// extracts file name from URL if nothing found
int p = fileURL.indexOf("?");
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, p > 0 ? p : fileURL.length());
// Strip parameters from the URL (if any)
String simpleUrl = (p > 0) ? fileURL.substring(0, p) : fileURL;
while (simpleUrl.endsWith("/")) {
simpleUrl = simpleUrl.substring(0, simpleUrl.length() - 1);
}
fileName = simpleUrl.substring(simpleUrl.lastIndexOf("/") + 1);
}
}
} else {
Expand Down
16 changes: 16 additions & 0 deletions src/test/java/dev/jbang/util/TestUtilDownloads.java
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,22 @@ void test2ReqWithETagUpdated(WireMockRuntimeInfo wmri) throws IOException, Inter
});
}

@Test
void testReqUrlWithParams(WireMockRuntimeInfo wmri) throws IOException {
stubFor(get(urlEqualTo("/test.txt?path=foo/bar"))
.andMatching(withoutHeader("If-None-Match"))
.andMatching(withoutHeader("If-Modified-Since"))
.willReturn(aResponse()
.withHeader("Content-Type",
"text/plain")
.withBody("test")));

String url = wmri.getHttpBaseUrl() + "/test.txt?path=foo/bar";
Path file = Util.downloadAndCacheFile(url);
assertThat(file.toFile(), anExistingFile());
assertThat(Util.readString(file), is("test"));
}

private static ValueMatcher<Request> withoutHeader(String hdr) {
return req -> MatchResult.of(!req.containsHeader(hdr));
}
Expand Down

0 comments on commit 7a8bc7d

Please sign in to comment.