BAEL-4856 Integrate progress when downloading

This commit is contained in:
Iulian Manda
2021-06-05 15:33:25 +03:00
parent 91dfad8bec
commit 34c9e82eee
6 changed files with 68 additions and 12 deletions
@@ -7,6 +7,9 @@ import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Objects;
import static org.springframework.http.HttpHeaders.CONTENT_LENGTH;
public class BinaryFileDownloader implements AutoCloseable {
@@ -22,7 +25,8 @@ public class BinaryFileDownloader implements AutoCloseable {
Request request = createRequest(url);
Response response = executeRequest(request);
ResponseBody responseBody = getResponseBodyOrFail(response);
return write(responseBody);
double length = getResponseLength(response);
return write(responseBody, length);
}
@NotNull
@@ -43,8 +47,12 @@ public class BinaryFileDownloader implements AutoCloseable {
return responseBody;
}
private long write(ResponseBody responseBody) throws IOException {
return writer.write(responseBody.byteStream());
private double getResponseLength(Response response) {
return Double.parseDouble(Objects.requireNonNull(response.header(CONTENT_LENGTH, "1")));
}
private long write(ResponseBody responseBody, double length) throws IOException {
return writer.write(responseBody.byteStream(), length);
}
@Override
@@ -9,12 +9,14 @@ public class BinaryFileWriter implements AutoCloseable {
private static final int CHUNK_SIZE = 1024;
private final OutputStream outputStream;
private final ProgressCallable progressCallable;
public BinaryFileWriter(OutputStream outputStream) {
public BinaryFileWriter(OutputStream outputStream, ProgressCallable progressCallable) {
this.outputStream = outputStream;
this.progressCallable = progressCallable;
}
public long write(InputStream inputStream) throws IOException {
public long write(InputStream inputStream, double length) throws IOException {
try (BufferedInputStream input = new BufferedInputStream(inputStream)) {
byte[] dataBuffer = new byte[CHUNK_SIZE];
int readBytes;
@@ -22,6 +24,7 @@ public class BinaryFileWriter implements AutoCloseable {
while ((readBytes = input.read(dataBuffer)) != -1) {
totalBytes += readBytes;
outputStream.write(dataBuffer, 0, readBytes);
progressCallable.onProgress(totalBytes / length * 100.0);
}
return totalBytes;
}
@@ -0,0 +1,7 @@
package com.baeldung.okhttp.download;
public interface ProgressCallable {
void onProgress(double progress);
}