Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide the first 1024 byte of the HTTP response body in case of a download error #57

Merged
merged 1 commit into from
Jan 7, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
Expand Down Expand Up @@ -105,7 +108,7 @@ public boolean download(DownloadSpec spec, Path finalLocation, boolean silent) t
} else if (response.statusCode() == 404) {
throw new FileNotFoundException(url.toString());
} else {
lastError = new IOException("Failed to download " + url + ": HTTP Status Code " + response.statusCode());
lastError = new IOException(buildRequestErrorMessage(url, response));
if (canRetryStatusCode(response.statusCode())) {
waitForRetry(response);
continue;
Expand Down Expand Up @@ -145,6 +148,33 @@ public boolean download(DownloadSpec spec, Path finalLocation, boolean silent) t
return true;
}

private static String buildRequestErrorMessage(URI url, HttpResponse<Path> response) {
// Read the first kb of data from the file
String bodyDetails = "";
try (var input = Files.newInputStream(response.body())) {
var decoder = StandardCharsets.UTF_8.newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPLACE);
decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
decoder.replaceWith(".");
bodyDetails = decoder.decode(ByteBuffer.wrap(input.readNBytes(1024))).toString();
if (bodyDetails.contains("<html")) {
// Printing HTML content on console is very pointless
bodyDetails = "<apparent HTML content>";
}
boolean hasMoreData = input.read() != -1;

if (hasMoreData) {
bodyDetails = "\nResponse: " + bodyDetails + "... " + (Files.size(response.body()) - 1024) + " byte omitted";
} else {
bodyDetails = "\nResponse: " + bodyDetails;
}
} catch (Exception ignored) {
System.out.println();
}

return "Failed to download " + url + ": HTTP Status Code " + response.statusCode() + bodyDetails;
}

private static void waitForRetry(HttpResponse<?> response) throws IOException {
// We only support the version of this that specifies the delay in seconds
var retryAfter = response.headers().firstValueAsLong("Retry-After").orElse(5);
Expand Down
Loading