BAEL-4856 Code review

This commit is contained in:
Iulian Manda 2021-06-16 19:19:45 +03:00
parent f3a5ca615e
commit 60b98a552e
1 changed files with 3 additions and 27 deletions

View File

@ -4,7 +4,6 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Objects;
@ -22,36 +21,13 @@ public class BinaryFileDownloader implements AutoCloseable {
}
public long download(String url) throws IOException {
Request request = createRequest(url);
Response response = executeRequest(request);
ResponseBody responseBody = getResponseBodyOrFail(response);
double length = getResponseLength(response);
return write(responseBody, length);
}
@NotNull
private Request createRequest(String url) {
return new Request.Builder().url(url).build();
}
@NotNull
private Response executeRequest(Request request) throws IOException {
return client.newCall(request).execute();
}
private ResponseBody getResponseBodyOrFail(Response response) {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
if (responseBody == null) {
throw new IllegalStateException("Response doesn't contain a file");
}
return responseBody;
}
private double getResponseLength(Response response) {
return Double.parseDouble(Objects.requireNonNull(response.header(CONTENT_LENGTH, "1")));
}
private long write(ResponseBody responseBody, double length) throws IOException {
double length = Double.parseDouble(Objects.requireNonNull(response.header(CONTENT_LENGTH, "1")));
return writer.write(responseBody.byteStream(), length);
}